[微信支付] 简单封装

直奔主题
注意:需要了解集成的可以查看demo,demo不能唤起支付或分享等功能,因为没有配置appKey,只能用作代码参考。

1、微信支付、登录、分享工具类:WXApiHelper.java

/**
 * 微信SDK帮助类
 */
public class WXApiHelper {

    private static final String WX_APP_ID = "wx666666";//TODO 微信相关
    private static final String WX_APP_SECRET = "66666666666666666";
    private static final String WX_SCOPE = "snsapi_userinfo";
    private static final String WX_STATE = "my_app_wx_login";
    private static final String WX_GRANT_TYPE = "authorization_code";
    private static final String WX_PACKAGE_VALUE = "Sign=WXPay";

    private static WXApiHelper mHelper;
    private final IWXAPI mWxApi;

    /**
     * APP.getInstance() 为Application的context
     */
    private WXApiHelper() {
        mWxApi = WXAPIFactory.createWXAPI(APP.getInstance(), WX_APP_ID, false);
        mWxApi.registerApp(WX_APP_ID);
    }

    public static WXApiHelper get() {
        if (mHelper == null) {
            mHelper = new WXApiHelper();
        }
        return mHelper;
    }

    /**
     * 微信登录
     */
    public void doWxLogin() {
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = WX_SCOPE;
        req.state = WX_STATE;

        mWxApi.sendReq(req);
    }

    /**
     * 微信支付
     *
     * @param payInfo 支付相关信息,需要从自己的服务器获取
     */
    public void doWxPay(PayInfo payInfo) {
        PayReq req = new PayReq();
        req.appId = WX_APP_ID;
        req.partnerId = payInfo.getPartnerid();
        req.prepayId = payInfo.getPrepayid();
        req.nonceStr = payInfo.getNoncestr();
        req.timeStamp = payInfo.getTimestamp();
        req.packageValue = WX_PACKAGE_VALUE;
        req.sign = payInfo.getSign();

        mWxApi.sendReq(req);
    }

    /**
     * 微信分享url给朋友
     *
     * @param title 标题
     * @param description 内容
     * @param url 分享的url
     */
    public void doShareUrlToWeChat(String title, String description, String url) {
        doShareUrl(title, description, url, SendMessageToWX.Req.WXSceneSession);
    }

    /**
     * 微信分享url到朋友圈
     * @param title 标题
     * @param description 内容
     * @param url 分享的url
     */
    public void doShareUrlToTimeline(String title, String description, String url) {
        doShareUrl(title, description, url, SendMessageToWX.Req.WXSceneTimeline);
    }

    private void doShareUrl(String title, String description, String url, int scene) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;

        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = description;
//        Bitmap thumbBmp = BitmapFactory.decodeResource(getResources(), R.drawable.send_music_thumb);
//        msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "webpage";
        req.message = msg;
        req.scene = scene;
//        req.userOpenId = getOpenId();

        mWxApi.sendReq(req);
    }

    //TODO 其他分享功能可以写到这里

    public void handleIntent(Intent intent, IWXAPIEventHandler handler) {
        mWxApi.handleIntent(intent, handler);
    }
}

2、实体类PayInfo.java

/**
 * 支付订单信息 (微信)
 */
public class PayInfo {

    //微信相关信息
    private String return_code;//返回代号
    private String return_msg;//
    private String appid;//应用ID
    private String mch_id;//
    private String noncestr;//随机字符串
    private String sign;//签名
    private String result_code;//结果代号
    private String prepayid;//预支付交易会话ID
    private String trade_type;//交易类型
    private String partnerid;//商户号
    private String timestamp;//时间戳
  
    //Getter 和 setter 方法这里就忽略不写
}

3、调用

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    private void doWeChatPay() {
        final PayInfo payInfo = new PayInfo();
        //TODO 实际的PayInfo需要调自己的服务器获取相关信息
        WXApiHelper.get().doWxPay(payInfo);
    }

    private void doWeChatShare() {
        WXApiHelper.get().doShareUrlToWeChat("活动", "这是一个公益活动", "公益活动的网页链接");
    }

    private void doWeChatLogin() {
        WXApiHelper.get().doWxLogin();
    }
}

4、支付回调WXPayEntryActivity.java

public class WXPayEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        WXApiHelper.get().handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        final int type = baseResp.getType();

        if (ConstantsAPI.COMMAND_PAY_BY_WX == type) {
            switch (baseResp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    //TODO 支付成功
                    break;
                case BaseResp.ErrCode.ERR_COMM:
                    Toast.makeText(this, "支付发生错误", Toast.LENGTH_LONG).show();
                    finish();
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    Toast.makeText(this, "已取消", Toast.LENGTH_LONG).show();
                    finish();
                    break;
                default:
                    Toast.makeText(this, "错误码:" + baseResp.errCode, Toast.LENGTH_LONG).show();
                    finish();
                    break;
            }
        }
    }
}

5、分享和登录回调WXEntryActivity.java

public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        WXApiHelper.get().handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        final int type = baseResp.getType();
        if (ConstantsAPI.COMMAND_SENDAUTH == type) {//登录
            switch (baseResp.errCode) {
                case BaseResp.ErrCode.ERR_OK:

                    final String code = ((SendAuth.Resp) baseResp).code;
                    getWxLoginInfo(code);

                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    Toast.makeText(this, "拒绝授权微信登录", Toast.LENGTH_LONG).show();
                    finish();
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    Toast.makeText(this, "已取消", Toast.LENGTH_LONG).show();
                    finish();
                    break;
                default:
                    Toast.makeText(this, "错误码:" + baseResp.errCode, Toast.LENGTH_LONG).show();
                    finish();
                    break;
            }
        } else if (ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX == type) {//分享
            finish();
        }
    }

    private void getWxLoginInfo(String code) {
        //TODO 通过微信SDK返回的code,请求自己的服务器获取用户信息。
    }
}

总结:经过上面的简单封装,微信支付、登录和分享功能都使用起来都变得非常简单。同时增加了复用性,在不同项目里只要拷贝文件小改一下就可以。最后就是这个demo只是简单封装,如果有哪里做的不正确或者哪里还可以优化的话,可以在评论区告诉下我,大家互相学习学习。

Demo:(喜欢的记得给个Star)

    原文作者:COKU2333
    原文地址: https://www.jianshu.com/p/dbc1382d6b46
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞