build.gradle中添加微信依赖
//微信
api 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'
调用微信类
/**
* Created by 14178 on 2018/1/19.
*/
public class WxLogin {
public static IWXAPI api;
public static Context mContext;
/**
* 初始化
*
* @param context
*/
public static void initWx(Context context) {
UIUtils.initContext(context);
mContext = context;
api = WXAPIFactory.createWXAPI(context, Constants.WX_APPID, true);
api.registerApp(Constants.WX_APPID);
final IWXAPI msgApi = WXAPIFactory.createWXAPI(context, null);
// 将该app注册到微信
msgApi.registerApp(Constants.WX_APPID);
}
/**
* 微信支付
*/
public static void payWx(BuyBean.DataBean.ParamsBean paramsBean) {
long timecurrentTimeMillis = System.currentTimeMillis();
long second = timecurrentTimeMillis / 1000;
HashMap<String, String> map = new HashMap<>();
String urlSign = RequestUtil.createUrlSign(map, true);
Log.e("TAG", "payWx: sign" + urlSign);
PayReq request = new PayReq();
request.appId = paramsBean.getAppid();
request.partnerId = paramsBean.getPartnerid();
request.prepayId = paramsBean.getPrepayid();
request.packageValue = "Sign=WXPay"; //固定值
request.nonceStr = paramsBean.getNoncestr(); //随机数
request.timeStamp = paramsBean.getTimestamp();
request.sign = paramsBean.getSign();
api.sendReq(request);
}
}
在Application中调用初始化微信
public class UserApplication extends Application {
private IWXAPI api;
private static UserApplication instance;
public static Context mAppContext = null;
public static UserApplication getInstance() {
return instance;
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
mAppContext = this;
WxLogin.initWx(this);
}
然后从后台请求到微信支付指定参数后,具体参数含义
拿到参数后,去拉起微信
public void toBuy(BuyBean buyBean) {
Log.e(TAG, "toBuy: " + buyBean.toString());
BuyBean.DataBean.ParamsBean params = buyBean.getData().getParams();
WxLogin.payWx(params);
}
微信支付的回调:
1.需要在项目中创建wxapi的包
在此包下创建WXPayEntryActivity文件
2.继承Activity, 实现IWXAPIEventHandler接口后
会重写两个方法:onReq()和onResp()
3.重写onCreate方法
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
api = WXAPIFactory.createWXAPI(this, Constants.WX_APPID);
api.handleIntent(getIntent(), this); //必须调用,否则wx不回调
}
4.重写onNewIntent方法
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
api.handleIntent(intent, this); //必须调用,否则wx不回调
}
5.onResp()方法
public void onResp(BaseResp baseResp) {
Log.d(TAG, "onPayFinish,errCode=" + baseResp.errCode);
finish();
}
微信会在onResp()中回调支付结果 errorcode 返回码对应下图