Android实现微信支付功能详解
1.集成微信支付SDK:
在build.gradle中,添加如下依赖
compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'
2.设置微信支付回调页面:
路径:项目包名.wxapi
名称:WXPayEntryActivity
public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
private IWXAPI api;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wx_pay_result);
api = WXAPIFactory.createWXAPI(this, "你的APP_ID");
api.handleIntent(getIntent(), this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
api.handleIntent(intent, this);
}
@Override
public void onResp(BaseResp resp) {
int errCode = resp.errCode;
}
}
errCode:说明
0:成功……展示成功页面。
-1:错误……可能的原因:签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等。
-2:用户取消……无需处理。发生场景:用户不支付了,点击取消,返回APP。
3.设置Manifest
<activity
android:name=".wxapi.WXPayEntryActivity"
android:exported="true"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="你的APP_ID" />
</intent-filter>
</activity>
4.设置MD5
public class MD5 {
private MD5() {
}
public final static String getMessageDigest(byte[] buffer) {
char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(buffer);
byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
return null;
}
}
}
5.发起微信支付
/**
* 注册微信支付
*/
private void registerWx() {
IWXAPI wxapi = WXAPIFactory.createWXAPI(context, null);
wxapi.registerApp("你的APP_ID");
}
/**
* 发起微信支付
*/
private void wxPay() {
PayReq payReq = new PayReq();
payReq.appId = "后台返回的appId";
payReq.partnerId = "后台返回的partnerId";
payReq.prepayId = "后台返回的prepayId";
payReq.packageValue = "后台返回的package";
payReq.nonceStr = "后台返回的nonceStr";
payReq.timeStamp = "后台返回的timeStamp";
payReq.signType = "后台返回的signType";
payReq.sign = signNum();
wxapi.sendReq(payReq);
}
/**
* 拼接sign
*/
public static String signNum() {
String stringA = "appid=" + "后台返回的appid" +
"&noncestr=" + "后台返回的noncestr" +
"&package=" + "后台返回的package" +
"&partnerid=" + "后台返回的partnerid" +
"&prepayid=" + "后台返回的prepayid" +
"×tamp=" + "后台返回的timestamp";
String stringSignTemp = stringA + "&key=" + "后台商户服务端的key";
String sign = MD5.getMessageDigest(stringSignTemp.getBytes()).toUpperCase();
return sign;
}
以上是 Android实现微信支付功能详解 的全部内容, 来源链接: utcz.com/z/357328.html