官方api:Android接入指南 | 微信开放文档
打开微信开放平台登录账户后点击创建应用
根据提示填写完相应的内容提交审核通过后,需要开通支付权限。
1.接着在你的项目工程build.gradle文件中添加微信支付依赖库
api 'com.tencent.mm.opensdk:wechat-sdk-android:+'
2.在你的包的根目录下,创建wxapi这个package包,注意必须是wxapi
3.在wxapi这个包下面再创建一个WXPayEntryActivity类,创建完成后记得在清单文件中注册
<activityandroid:name=".wxapi.WXPayEntryActivity"android:exported="true"android:launchMode="singleTop">
</activity>
4.如果你的targetSdkVersion是30以上的话,需要在主工程的AndroidManifest.xml 中增加标签,如果不配置的话可能无法正常拉起微信支付
<queries><package android:name="com.tencent.mm" />
</queries>
5.WXPayEntryActivity相关代码实现
package com.ranlegeran.wechatpaydemo.wxapi;import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;import java.util.List;public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {private static final String TAG = "WXPayEntryActivity";private IWXAPI mIWXAPI;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);mIWXAPI = WXAPIFactory.createWXAPI(this, "你申请的APPID");mIWXAPI.handleIntent(getIntent(), this);}@Overrideprotected void onNewIntent(Intent intent) {super.onNewIntent(intent);setIntent(intent);mIWXAPI.handleIntent(intent, this);}@Overridepublic void onReq(BaseReq baseReq) {switch (baseReq.getType()){}}//第三方应用发送到微信的请求处理后的响应结果,会回调到该方法@Overridepublic void onResp(BaseResp baseResp) {Log.e(TAG, "onResp---> " + baseResp.errCode);if (baseResp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {if (baseResp.errCode == 0) {//支付成功相关操作Log.e(TAG, "onResp---> 支付成功" + baseResp.errCode);} else if (baseResp.errCode == -1) {//支付失败相关操作Log.e(TAG,"onResp---> 支付失败" + baseResp.errCode);} else if (baseResp.errCode == -2) {//支付取消相关操作Log.e(TAG,"onResp---> 用户取消" + baseResp.errCode);}finish();}}/*** 判断 用户是否安装微信客户端*/public static boolean isWxAvilible(Context context) {final PackageManager packageManager = context.getPackageManager();List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);if (pinfo != null) {for (int i = 0; i < pinfo.size(); i++) {String pn = pinfo.get(i).packageName;if (pn.equals("com.tencent.mm")) {return true;}}}return false;}
}
5.在MainActivity中去调用微信支付,在onCreate方法中把AppId注册到微信,布局中放置了一个Button按钮用来点击调用
toWeChatPay()方法,这个方法中是模拟请求解析后端返回的数据,请根据自己后端返回的实际数据去处理
package com.ranlegeran.wechatpaydemo;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;
import android.widget.Button;import com.ranlegeran.wechatpaydemo.wxapi.WXPayEntryActivity;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;import org.json.JSONException;
import org.json.JSONObject;import java.io.IOException;public class MainActivity extends AppCompatActivity {private Button mBtnWeChatPay;//IWXAPI 是第三方app和微信通信的openApi接口private IWXAPI mIWXAPI;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//通过WXAPIFactory工厂,获取IWXAPI的实例mIWXAPI = WXAPIFactory.createWXAPI(this,"你申请的APPID",true);//将应用的appId注册到微信mIWXAPI.registerApp("你申请的APPID");mBtnWeChatPay = this.findViewById(R.id.call_wechat_pay);mBtnWeChatPay.setOnClickListener(v -> {toWeChatPay();});}/*** 这里模拟调用后端接口解析返回的数据* 只是模拟,请根据后台返回的实际情况解析*/private void toWeChatPay() {Retrofit mRetrofit = RetrofitManager.getInstance().getRetrofit();Api mApi = mRetrofit.create(Api.class);Call<ResponseBody> mCall = mApi.postWeChatPay(mModeltype,payType,mMethod,orderId,mOpenappid);mCall.enqueue(new Callback<ResponseBody>() {@Overridepublic void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {ResponseBody mBody = response.body();try {JSONObject rootObject = new JSONObject(mBody.string());int code = rootObject.optInt("code");String msg = rootObject.optString("msg");String data = rootObject.optString("data");if (code != 1) {toast(msg);return;} else {JSONObject dataObject = new JSONObject(data);String appid = dataObject.getString("appid");String partnerid = dataObject.getString("partnerid");String prepayid = dataObject.getString("prepayid");String timestamp = dataObject.getString("timestamp");String noncestr = dataObject.getString("noncestr");String spackage = dataObject.getString("package");String sign = dataObject.getString("sign");//判断手机是否安装了微信客户端if (!WXPayEntryActivity.isWxAvilible(MainActivity.this)) {toast("您还没有安装微信客户端");return;}transferWxPay(appid,partnerid,prepayid,timestamp,noncestr,spackage,sign);}} catch (JSONException e) {throw new RuntimeException(e);} catch (IOException e) {throw new RuntimeException(e);}}@Overridepublic void onFailure(Call<ResponseBody> call, Throwable t) {toast("微信支付" + t.getMessage());}});}private void transferWxPay(String appid, String partnerid, String prepayid,String timestamp, String noncestr, String spackage,String sign) {PayReq mPayReq = new PayReq();//AppIdmPayReq.appId = appid;//微信支付分配的商户号mPayReq.partnerId = partnerid;//微信返回的支付交易会话IDmPayReq.prepayId = prepayid;//暂填写固定值Sign=WXPaymPayReq.packageValue = "Sign=WXPay";//随机字符串,不长于32位。推荐随机数生成算法mPayReq.nonceStr = noncestr;//时间戳mPayReq.timeStamp = timestamp;//签名mPayReq.sign = sign;mIWXAPI.sendReq(mPayReq);}
}
最后附一张拉起微信支付的截图