微信支付開發(fā)完整流程與-1”閃屏”解決
文檔說明
現(xiàn)在的APP里面只要有支付的應該都會用到微信支付,但是在開發(fā)的過程中會遇到各種問題,很多人都會說官方文檔寫的稍微有那么一點看不懂晒哄,同感横辆!不想懷疑人生的,就看小白的文檔就行俏险,保證讓你舒服順利的肴楷,,荠呐,赛蔫,不遇到各種頭疼問題。
嘿嘿嘿,泥张,低調低調呵恢,正文走起
開發(fā)流程
這里我們分五個步驟:
1 :去找你們產品要微信開放平臺的賬號密碼。
簽名生成工具
2 :去微信官方文檔下載一個 **簽名生成工具 **: 簽名生成工具下載地址
打包簽名注意事項
3 : 簽名工具安裝到手機上之后媚创,把你們的 項目打包 打一個 release 包安裝到手機上渗钉,( 切記 :“打包要打個release包不要打debug包,也不是讓你run運行到手機上面钞钙,因為你上線的時候用的是正式包(release包)上線的”)鳄橘,安裝到手機上之后,打開你上一步下載的“簽名生成工具”)芒炼,把你項目的 包名 放在“輸入框”里面瘫怜,點擊按鈕“Get Signature”會在按鈕下面生成一串綠色簽名,保存起來一會要用到(如圖)本刽。(此刻鲸湃,一定有童鞋會說我怎么沒有看到生成綠色的一串簽名赠涮?怎么提示“NameNotFoundExcption signs is null”(),正如其報錯,肯定是你包名寫錯啦暗挑,或者就是你手機上忘記安裝你們的App啦...)
應用平臺簽名更改
4 :這時候肯定有童鞋會問生成的這個簽名是干嘛的有什么用笋除?生成的簽名是你們App的一個唯一標識,拿著這個標識(簽名)去微信開放平臺的管理中心 / 修改應用 / 修改開發(fā)信息炸裆,給Android的開發(fā)信息給填寫一下(如圖)垃它,簽名 包名填寫完保存一下。
5 : 流程的最后一步:到微信開放平臺的 管理中心 / 應用中心 把你們的AppSecret和AppID保存起來晒衩。
sequenceDiagram
??->> ? ?: 直接上代碼嘍!
支付依賴
//微信支付
implementation 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'
App支付集成代碼
WXPayUtils
package com.xyxy.app.wx;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import org.cocos2dx.wolf.utils.ToastUtils;
import java.security.MessageDigest;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
/**
*
* 2018/12/5
*
* W
*
* */
public class WXPayUtils {
private IWXAPI iwxapi; //微信支付api
private WXPayBuilder builder;
private WXPayUtils(WXPayBuilder builder) {
this.builder = builder;
}
/**
* 調起微信支付的方法,不需要在客戶端簽名
**/
public void toWXPayNotSign(Context context) {
iwxapi = WXAPIFactory.createWXAPI(context, null); //初始化微信api
iwxapi.registerApp(builder.getAppId()); //注冊appid appid可以在開發(fā)平臺獲取
Runnable payRunnable = new Runnable() { //這里注意要放在子線程
@Override
public void run() {
PayReq request = new PayReq(); //調起微信APP的對象
//下面是設置必要的參數(shù)嗤瞎,也就是前面說的參數(shù),這幾個參數(shù)從何而來請看上面說明
request.appId = builder.getAppId();
request.partnerId = builder.getPartnerId();
request.prepayId = builder.getPrepayId();
request.packageValue = builder.getPackageValue();
request.nonceStr = builder.getNonceStr();
request.timeStamp =builder.getTimeStamp();
request.sign = builder.getSign();
iwxapi.sendReq(request);//發(fā)送調起微信的請求
}
};
Thread payThread = new Thread(payRunnable);
payThread.start();
}
/**
* 調起微信支付的方法,需要在客戶端簽名
**/
public void toWXPayAndSign(Context context, String appid, final String key) {
iwxapi = WXAPIFactory.createWXAPI(context, null); //初始化微信api
iwxapi.registerApp(appid); //注冊appid appid可以在開發(fā)平臺獲取
Runnable payRunnable = new Runnable() { //這里注意要放在子線程
@Override
public void run() {
PayReq request = new PayReq(); //調起微信APP的對象
//下面是設置必要的參數(shù),也就是前面說的參數(shù),這幾個參數(shù)從何而來請看微信支付參數(shù)說明文檔
request.appId = builder.getAppId();
request.partnerId = builder.getPartnerId();
request.prepayId = builder.getPrepayId();
request.packageValue = "Sign=WXPay";
// request.nonceStr = genNonceStr();
// request.timeStamp = String.valueOf(genTimeStamp());
request.nonceStr = builder.getNonceStr();
request.timeStamp = builder.getTimeStamp();
// request.sign = builder.getSign();
//簽名
LinkedHashMap<String, String> signParams = new LinkedHashMap<>();
signParams.put("appid", request.appId);
signParams.put("noncestr", request.nonceStr);
signParams.put("package", "Sign=WXPay");
signParams.put("partnerid", request.partnerId);
signParams.put("prepayid", request.prepayId);
signParams.put("timestamp", request.timeStamp);
request.sign = genPackageSign(signParams, key);
boolean b = iwxapi.sendReq(request);//發(fā)送調起微信的請求
Log.d("WXPayUtils", "b:" + b);
}
};
Thread payThread = new Thread(payRunnable);
payThread.start();
if (!iwxapi.isWXAppInstalled()){
ToastUtils.show(context,"請安裝微信听系!", Toast.LENGTH_SHORT);
}
}
/**
* 調起微信APP支付贝奇,簽名
* 生成簽名
*/
private String genPackageSign(LinkedHashMap<String, String> params, String key) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(entry.getKey());
sb.append('=');
sb.append(entry.getValue());
sb.append('&');
}
sb.append("key=");
sb.append(key);
String packageSign = getMessageDigest(sb.toString().getBytes()).toUpperCase();
return packageSign;
}
/**
* md5加密
*
* @param buffer
* @return
*/
private 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;
}
}
/**
* 獲取隨機數(shù)
*
* @return
*/
private String genNonceStr() {
Random random = new Random();
return getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
}
/**
* 獲取時間戳
*
* @return
*/
private long genTimeStamp() {
return System.currentTimeMillis() / 1000;
}
public static class WXPayBuilder {
public String appId;
public String partnerId;
public String prepayId;
public String packageValue;
public String nonceStr;
public String timeStamp;
public String sign;
public WXPayUtils build() {
return new WXPayUtils(this);
}
public String getAppId() {
return appId;
}
public WXPayBuilder setAppId(String appId) {
this.appId = appId;
return this;
}
public String getPartnerId() {
return partnerId;
}
public WXPayBuilder setPartnerId(String partnerId) {
this.partnerId = partnerId;
return this;
}
public String getPrepayId() {
return prepayId;
}
public WXPayBuilder setPrepayId(String prepayId) {
this.prepayId = prepayId;
return this;
}
public String getPackageValue() {
return packageValue;
}
public WXPayBuilder setPackageValue(String packageValue) {
this.packageValue = packageValue;
return this;
}
public String getNonceStr() {
return nonceStr;
}
public WXPayBuilder setNonceStr(String nonceStr) {
this.nonceStr = nonceStr;
return this;
}
public String getTimeStamp() {
return timeStamp;
}
public WXPayBuilder setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
return this;
}
public String getSign() {
return sign;
}
public WXPayBuilder setSign(String sign) {
this.sign = sign;
return this;
}
}
}
WXPayEntryActivity
WXPayEntryActivity 要放在 wxapi 包下
packagecom.xyxy.app.wxapi;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
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 com.umeng.analytics.MobclickAgent;
import org.cocos2dx.wolf.MyApplication;
import org.cocos2dx.wolf.utils.ShareUtils;
import java.util.HashMap;
import java.util.Map;
/**
*
* 2018/12/5
*
* W
*
* */
public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
private IWXAPI api;
private String AppID=;//微信開放平臺AppID
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
api = WXAPIFactory.createWXAPI(this, AppID);
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) {
Log.d("WXPayEntryActivity", "微信返回錯誤碼:" + resp.errCode);
if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
if (resp.errCode == 0) {
Toast.makeText(this, "支付成功", Toast.LENGTH_LONG).show();
} else {
Log.e("java", "onResp: " + resp.errCode);
Toast.makeText(this, "取消支付", Toast.LENGTH_LONG).show();
}
finish();
}
}
@Override
public void onReq(BaseReq baseReq) {
}
}
MainActivity
Android代碼調用
String appid = data.getAppid();
IWXAPI wxapi = WXAPIFactory.createWXAPI(app,appid,false);//初始化微信api
wxapi.registerApp(data.getAppid());
WXPayUtils.WXPayBuilder builder = new WXPayUtils.WXPayBuilder();
builder.setAppId(data.getAppid())
.setPrepayId(data.getPrepayid())
.setPackageValue(data.getPackageX())
.setNonceStr(data.getNoncestr())
.setTimeStamp(data.getTimestamp())
.setSign(data.getSign())
.build()
.toWXPayNotSign(app);
AndroidManifest.xml
//微信支付
<activity
android:name=".wxapi.WXPayEntryActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:exported="true"
android:launchMode="singleInstance"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="微信AppID"/>
</intent-filter>
</activity>
支付返回 “-1” 與 “閃屏”的原因解決
1,微信簽名要用release包生成 測試的時候也要打release包安裝到手機測試靠胜,不能run運行掉瞳,否則 閃屏
2,AppID是否正確
3浪漠,AndroidManifest.xml的 name 固定是 name=".wxapi.WXPayEntryActivity"調用微信
完工陕习!