前言
最近做的一個需求紧唱,要求app需要拉起小程序進行支付操作,之前做reavt-native開發(fā)內部集成微信的支付隶校, 分享琼蚯,第三方登錄等操作。但是默認的庫中不包含拉起小程序的類惠况。
小程序與app關聯(lián)的問題這里就不做描述了。 主要需要小程序的原始Id和app的id
AndroidManifest.xml文件修改
<activity
android:name="包名.wxapi.WXEntryActivity"
android:label="@string/app_name"
android:exported="true"
android:configChanges="keyboardHidden|orientation|screenSize"
android:launchMode="singleTask"
android:taskAffinity="包名"
android:theme="@android:style/Theme.Translucent.NoTitleBar" />
/>
react-native-WeChat index.js 文件增加拉起小程序方法
/**
* wechat launchMini
* @param {Object} data
* @returns {Promise}
*/
export function launchMini(data) {
// FIXME(Yorkie): see https://github.com/yorkie/react-native-wechat/issues/203
// Here the server-side returns params in lowercase, but here SDK requires timeStamp
// for compatibility, we make this correction for users.
function correct(actual, fixed) {
if (!data[fixed] && data[actual]) {
data[fixed] = data[actual];
delete data[actual];
}
}
// 參數設置 這里距離為訂單Id
correct('orderId', 'orderId');
// FIXME(94cstyles)
// Android requires the type of the timeStamp field to be a string
if (Platform.OS === 'android') data.timeStamp = String(data.timeStamp)
return new Promise((resolve, reject) => {
WeChat.launchMini(data, result => {
if (result) reject(result);
});
});
}
android目錄下build.gradle文件下增加依賴
api 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:5.3.1'
WeChatModule.java增加方法
@ReactMethod
public void launchMini(ReadableMap data, Callback callback) {
String id = "";
if (data.hasKey("orderId")) {
id = data.getString("orderId");
}
String appId = ""; // 填應用AppId
IWXAPI api = WXAPIFactory.createWXAPI(getCurrentActivity(), appId);
WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
req.userName = ""; // 填小程序原始id
req.path = "/pages/user/pay?id=" + id
////拉起小程序頁面的可帶參路徑宁仔,不填默認拉起小程序首頁稠屠,對于小游戲,可以只傳入 query 部分,來實現傳參效果权埠,如:傳入 "?foo=bar"榨了。
req.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW;// 可選打開 開發(fā)版,體驗版和正式版
callback.invoke(api.sendReq(req) ? null : INVOKE_FAILED);
}
## public void onResp(BaseResp baseResp) 甚至回調方法添加
else if (baseResp instanceof WXLaunchMiniProgram.Resp) {
WXLaunchMiniProgram.Resp resp = (WXLaunchMiniProgram.Resp) (baseResp);
map.putString("type", "WXLaunchMiniProgram.Resp");
map.putString("returnKey", resp.extMsg);
}
react-native端需要進行監(jiān)聽
WeChat.addListener("WXLaunchMiniProgram.Resp", response => {
//returnKey 自己約定返回參數
if(response && response.returnKey == 'success') {
} else {
Toast.info('支付失敗');
}
});
// 調用:
WeChat.launchMini({});