안 탁 웨 이 신 로그 인, 공유, 지불

1. 준비 작업
  • 위 챗 오픈 플랫폼 에 계 정 을 등록 하고 WX 획득AppID。
  • 의존 도 추가: api 'com. tencent. mm. opensdk: wechat - sdk - android - wthout - mta: +'
  • BaseApplication 에 위 챗 로그 인 wxapi = WXAPIFactory. createWXAPI (this, Configure. WX AppID, false) 를 등록 합 니 다.wxapi.registerApp(Configure.WX_AppID);
  • 목록 파일 에 추가
        
    
    
        
    
  • 2. 위 챗 로그 인 및 공유 의 실현 클래스
    public class WXEntryActivity extends FragmentActivity implements IWXAPIEventHandler {
        private static final int RETURN_MSG_TYPE_LOGIN = 1;
        private static final int RETURN_MSG_TYPE_SHARE = 2;
        private OkHttpClient okHttpClient;
        private boolean isShareMoney = false;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //     onResp,        
            BaseApplication.getWxApi().handleIntent(getIntent(), this);
        }
    
    
    
        /**
         *              ,       
         *
         * @param baseReq
         */
        @Override
        public void onReq(BaseReq baseReq) {
    
        }
        /**
         *          app   ,     
         *
         * @param showReq
         */
        private void goToShowMsg(ShowMessageFromWX.Req showReq) {
    
        }
        /**
         *                      ,       
         * app       ,         
         *
         * @param baseResp
         */
        @Override
        public void onResp(BaseResp baseResp) {
            switch (baseResp.errCode) {
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    finish();
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    finish();
                    if (RETURN_MSG_TYPE_SHARE == baseResp.getType()) {
                        ToastUtils.showToast("    ");
                    } else {
                        ToastUtils.showToast("    ");
                    }
                    break;
                case BaseResp.ErrCode.ERR_OK:
                    switch (baseResp.getType()) {
                        case RETURN_MSG_TYPE_LOGIN:
                            finish();
                            //        code,      access_token
                            String code = ((SendAuth.Resp) baseResp).code;
                            //  code        (UnionID  )
                            getWxUnionID(code);
                            break;
                        case RETURN_MSG_TYPE_SHARE:
                            String transaction = baseResp.transaction;
                            if (transaction != null && Configure.SHARE_MONEY1.equals(transaction)) {
                                ShareMoneyDialog.initInstance(this).show(getFragmentManager(), "WXEntryActivity");
                            }else if (transaction != null && Configure.SHARE_MONEY2.equals(transaction)) {
                                ShareMoneyDialog.initInstance(this).show(getFragmentManager(), "WXEntryActivity");
                            }else if (transaction != null && "miniProgram".equals(transaction)) {
                                ToastUtils.showToast("       ");
                                finish();
                            } else {
                                ToastUtils.showToast("    ");
                                finish();
                            }
                            break;
                    }
                    break;
                default:
                    finish();
                    break;
            }
        }
    
        /**
         *         (UnionID  )
         *
         * @param code
         */
        private void getWxUnionID(String code) {
            ToastUtils.showLoadDialog("     ...");
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Configure.WX_AppID + "&secret=" + Configure.WX_AppSecret + "&code=" + code + "&grant_type=authorization_code";
            okHttpClient = new OkHttpClient();
            Request request = new Request.Builder().get().url(url).build();
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    ToastUtils.closeLoadDialog();
                    ToastUtils.showToast(e.getMessage());
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    ToastUtils.closeLoadDialog();
                    String result = response.body().string();
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(result);
                        String unionid = (String) jsonObject.get("unionid");
                        // TODO: 2018/5/15       unionid
                        WXLoginO(unionid);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (result == null) {
                        return;
                    }
    
                }
            });
        }
    
        /**
         *        
         *
         * @param unionid
         */
        private void WXLoginO(final String unionid) {
            ToastUtils.showLoadDialog("    ...");
            ApiService.checkUnionId(unionid).subscribe(new CallBack() {
    
                @Override
                protected void errorBody(String code, String message, String result) {
                    ToastUtils.closeLoadDialog();
    
                    if ("2".equals(code)) {//     
    //                    ACache.getAsString(AcacheKey.UNIONID);
                        RouterUtils.openPage(RouterPath.REGISTER_PAGE, "unionid", unionid);
                        return;
                    }
                    if ("3".equals(code)) {
                        ToastUtils.showToast("       ,       ");
                    } else {
                        ToastUtils.showToast(message);
                    }
                }
    
                @Override
                protected void requestBody(LoginEntity data, String message) {
                    ToastUtils.closeLoadDialog();
                    //    ID
                    PreferencesUtils.putString(AcacheKey.MANUFACTUREID, data.getManufacturerId());
                    PreferencesUtils.putString(AcacheKey.SESSIONID, data.getSessionId());
                    PreferencesUtils.putString(AcacheKey.USERID, data.getUserId());
                    PreferencesUtils.putString(AcacheKey.USER_VIP, data.getPayStatus());
                    JPushInterface.setAlias(BaseApplication.getCurrentActivity(), data.getUserId(), new TagAliasCallback() {
                        @Override
                        public void gotResult(int i, String s, Set set) {
    
                        }
                    });
                    String easemobUserName = data.getEasemobUserName();
                    String easemobPassWord = data.getEasemobPassWord();
                    //    
                    if (easemobUserName != null && easemobPassWord != null) {
    //                    ToastUtils.showLoadDialog("      ...");
                        HXLoginUtils.hxLogin(easemobUserName, easemobPassWord);
                    } else {
                        JPushInterface.resumePush(BaseApplication.getInstance());
                        RouterUtils.openPage(RouterPath.MAIN_OPERATOR);
                    }
    
                }
            });
        }
    }
    

    3. 위 챗 결제 의 실현 유형
    public class WXPayEntryActivity extends BaseActivity implements IWXAPIEventHandler {
        @Override
        protected int createView() {
            return R.layout.activity_wxpay_entry;
        }
        @Override
        protected void initData() {
            //     onResp,        
            BaseApplication.getWxApi().handleIntent(getIntent(), this);
        }
        @Override
        public void onReq(BaseReq baseReq) {
        }
        @Override
        public void onResp(BaseResp resp) {
            /**
             *      :https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=8_5
             */
            if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
                int code = resp.errCode;
                switch (code) {
                    case 0:
                        ToastUtils.showToast("    ");
                        PayResp myResp = (PayResp) resp;
                        String transaction = myResp.extData;
                        if (transaction != null && Configure.BUY_SUCCESS1.equals(transaction)) {//      
                            EventbusUtils.sendEvent(new Event(EventC.UPDATE_BUY_MSG_INFO));
                        }
                        if (transaction != null && Configure.BUY_SUCCESS2.equals(transaction)) {//      
                            EventbusUtils.sendEvent(new Event(EventC.UPDATE_BUY_VIP_INFO));
                            PreferencesUtils.putString(AcacheKey.USER_VIP, "3");
                        }
                        finish();
                        break;
                    case -1:
                        finish();
                        //           :    、   APPID、    APPID   、   APPID       、     
                        ToastUtils.showToast("    ");
                        break;
                    case -2:
                        finish();
                        ToastUtils.showToast("    ");
                        break;
                }
            }
        }
    }
    

    4. 위 챗 공유 도구 클래스
    public class ShareFriendsUtils {
        private static WXMediaMessage wxMediaMessage;
    
        /**
         *  url      
         *
         * @param mContext
         * @param url
         * @param title
         * @param imgUrl
         */
        public static void shareToFriends(Context mContext, String url, String title, String imgUrl, final String myTransaction) {
            if (!BaseApplication.getWxApi().isWXAppInstalled()) {
                ToastUtils.showToast("         ");
                return;
            }
            //   WXWebpageObject  ,  url
            WXWebpageObject wxWebpageObject = new WXWebpageObject();
            wxWebpageObject.webpageUrl = url;
            // WXWebpageObject     WXMediaMessage   ,       、     
            wxMediaMessage = new WXMediaMessage(wxWebpageObject);
            wxMediaMessage.title = title;
            Glide.with(mContext).load(imgUrl).into(new SimpleTarget() {
                @Override
                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition super Drawable> transition) {
                    Bitmap bitmap = ImagUtils.drawableToBitmap(resource);
                    //     
                    Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 80, 80, true);
                    wxMediaMessage.setThumbImage(scaledBitmap);
                    //    req
                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    //transaction    
                    req.transaction = myTransaction;
                    req.message = wxMediaMessage;
                    //      
                    req.scene = SendMessageToWX.Req.WXSceneTimeline;
                    //        
                    BaseApplication.getWxApi().sendReq(req);
                }
            });
        }
    
        /**
         *         
         *
         * @param bitmap
         */
        public static void shareImgeToFriends(Bitmap bitmap) {
            if (!BaseApplication.getWxApi().isWXAppInstalled()) {
                ToastUtils.showToast("         ");
                return;
            }
            if (bitmap==null) {
                return;
            }
            //   WXWXImageObject   WXMediaMessage  
            WXImageObject wxImageObject = new WXImageObject(bitmap);
            WXMediaMessage wxMediaMessage = new WXMediaMessage();
            wxMediaMessage.mediaObject = wxImageObject;
            //     
            Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 50, 100, true);
            wxMediaMessage.setThumbImage(scaledBitmap);
    
            //    req
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            //transaction    
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = wxMediaMessage;
            //      
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
            //        
            BaseApplication.getWxApi().sendReq(req);
        }
    
        /**
         *        
         *
         * @param bitmap
         */
        public static void shareImgeToMyFriend(Bitmap bitmap) {
            if (!BaseApplication.getWxApi().isWXAppInstalled()) {
                ToastUtils.showToast("         ");
                return;
            }
            if (bitmap==null) {
                return;
            }
            //   WXWXImageObject   WXMediaMessage  
            WXImageObject wxImageObject = new WXImageObject(bitmap);
            WXMediaMessage wxMediaMessage = new WXMediaMessage();
            wxMediaMessage.mediaObject = wxImageObject;
            //     
            Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 50, 100, true);
            wxMediaMessage.setThumbImage(scaledBitmap);
    
            //    req
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            //transaction    
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = wxMediaMessage;
            //       
            req.scene = SendMessageToWX.Req.WXSceneSession;
            //        
            BaseApplication.getWxApi().sendReq(req);
        }
        /**
         *        
         */
        public static void shareProgramObject(String title,String path){
            if (!BaseApplication.getWxApi().isWXAppInstalled()) {
                ToastUtils.showToast("         ");
                return;
            }
            WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
            miniProgramObj.webpageUrl = "http://www.hellokeeper.com/lsf/client-download.html"; //           
            miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;//    :0,   :1,   :2
            miniProgramObj.userName = "gh_ee782e862a53";     //      id
            miniProgramObj.path = path;            //       
            WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
            msg.title = title;                    //      title
            msg.description = "     Desc";               //      desc
            Bitmap bitmap = BitmapFactory.decodeResource(BaseApplication.getCurrentActivity().getResources(), R.mipmap.mini_banner1);
            //     
            Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 833, 666, true);
            msg.setThumbImage(scaledBitmap);                     //          ,  128k
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = ("miniProgram");
            req.message = msg;
            req.scene = SendMessageToWX.Req.WXSceneSession;  //        
            BaseApplication.getWxApi().sendReq(req);
        }
    }
    

    5. 위 챗 결제 도구 류
    public class WXpayUtils {
        /**
         *         
         **/
        public static void toWXPay( final String partnerId, final String prepayId, final String nonceStr,
                                   final String timeStamp, final String sign, final String packageValue, final String tag) {
            if (! BaseApplication.getWxApi().isWXAppInstalled()) {
                ToastUtils.showToast("       ");
                return;
            }
            //          
            Runnable payRunnable = new Runnable() {
                @Override
                public void run() {
                    PayReq request = new PayReq(); //       
    
                    //       ,                     ,         
                    request.appId = Configure.WX_AppID;
                    request.partnerId = partnerId;
                    request.prepayId = prepayId;
                    request.packageValue = packageValue;
                    request.nonceStr = nonceStr;
                    request.timeStamp = timeStamp;
                    request.sign = sign;
                    //    
                    request.extData = tag;
                    BaseApplication.getWxApi().sendReq(request);//         
                }
            };
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }
    }
    

    좋은 웹페이지 즐겨찾기