車后市APP:Cordova項目轉換并兼容公眾號總結
2022年5月12日 8462 5Cordova與React Native一樣,是目前主流的Hybrid模式APP開發框架,而相對于H5代碼的銜接,Cordova在這方面的兼容性更好一些,因為它沒有定義具體的語法,將具體的業務邏輯留給ionic或者AngularJS等單頁應用的開發框架去實現,自己負責與原生設備接口交互,包括相機(拍照)、相冊、GPS定位、掃碼、文件管理、支付等等。作為一款車后市APP,酷愛洗車APP是基于延譽寶會員管理系統深度定制合作的物聯網項目,隨著業務的不斷擴展,APP端的已經滿足自助洗車客戶對移動端應用入口的需求,因此,開發小程序和公眾號成為運營推廣的必然要求。但是考慮開發成本,特別是后期的運營維護,如果兩套代碼,必然增加后續維護的負擔,造成系統升級的項目投入增加,因此,最好的解決方案,就是實現Cordova項目可以兼容微信公眾號,如此這樣,iPhone、安卓和公眾號三個入口使用一份代碼,便于BUG修復,并提高系統運維的效率,從而在服務器端大數據運維投入不變的前提下,減輕客戶端的技術投入壓力。
Cordova與React Native一樣,是目前主流的Hybrid模式APP開發框架,而相對于H5代碼的銜接,Cordova在這方面的兼容性更好一些,因為它沒有定義具體的語法,將具體的業務邏輯留給ionic或者AngularJS等單頁應用的開發框架去實現,自己負責與原生設備接口交互,包括相機(拍照)、相冊、GPS定位、掃碼、文件管理、支付等等。
作為一款車后市APP,酷愛洗車APP是基于延譽寶會員管理系統深度定制合作的物聯網項目,隨著業務的不斷擴展,APP端的已經滿足自助洗車客戶對移動端應用入口的需求,因此,開發小程序和公眾號成為運營推廣的必然要求。但是考慮開發成本,特別是后期的運營維護,如果兩套代碼,必然增加后續維護的負擔,造成系統升級的項目投入增加,因此,最好的解決方案,就是實現Cordova項目可以兼容微信公眾號,如此這樣,iPhone、安卓和公眾號三個入口使用一份代碼,便于BUG修復,并提高系統運維的效率,從而在服務器端大數據運維投入不變的前提下,減輕客戶端的技術投入壓力。
實現將Cordova APP轉公眾號項目,主要解決以下幾個接口的兼容:
1、微信粉絲身份的自動獲取。
這個步驟在原生APP開發中是沒有的,也不需要的,因此需要服務器接口支持。對應的AngularJS的代碼如下:
if(is_in_weixin_browser && !is_in_wxa_browser){
//公眾號更換頭像
console.log(is_in_weixin_browser);
console.log(is_in_wxa_browser);$scope.get_weixin_jssdk_params();
對應的get_weixin_jssdk_params函數處理過程如下,除了獲取openid之外,還需要控制分享轉發的圖片、文字和鏈接。
//請求接口,獲取微信JSSDK參數
$scope.get_weixin_jssdk_params = function () {var current_url = document.location.href;
$http({
method: ‘post’,//請求方式
url: http_server + “/index.php?g=Yanyubao&m=Kuaicar&a=weixin_jssdk_params”,//請求地址
data: {‘sellerid’: 123, ‘userid’: 456, ‘checkstr’: 789, ‘current_url’:current_url}//請求參數,如果使用JSON格式的對象則可為 data: JSON.stringify(obj),
//timeout: 8000//請求等待時間
})
.success(function (data) {
// console.log(1111111);
// console.log(data);
// console.log(1111111);
if (data.code == ‘1’) {if (typeof WeixinJSBridge == “undefined”){
if( document.addEventListener ){
document.addEventListener(‘WeixinJSBridgeReady’, onBridgeReady, false);
}else if (document.attachEvent){
document.attachEvent(‘WeixinJSBridgeReady’, onBridgeReady);
document.attachEvent(‘onWeixinJSBridgeReady’, onBridgeReady);
}
}else{
onBridgeReady();
}wx.config({
debug: false, /* 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時才會打印。*/
appId: data.signPackage[‘appId’], /* 必填,公眾號的唯一標識*/
timestamp: data.signPackage[‘timestamp’], /* 必填,生成簽名的時間戳*/
nonceStr: data.signPackage[‘nonceStr’], /* 必填,生成簽名的隨機串*/
signature: data.signPackage[‘signature’],/* 必填,簽名,見附錄1*/
jsApiList: [
‘checkJsApi’,
‘onMenuShareTimeline’,
‘onMenuShareAppMessage’,
‘onMenuShareQQ’,
‘onMenuShareWeibo’,
‘hideMenuItems’,
‘showMenuItems’,
‘hideAllNonBaseMenuItem’,
‘showAllNonBaseMenuItem’,
‘translateVoice’,
‘startRecord’,
‘stopRecord’,
‘onRecordEnd’,
‘playVoice’,
‘pauseVoice’,
‘stopVoice’,
‘uploadVoice’,
‘downloadVoice’,
‘chooseImage’,
‘previewImage’,
‘uploadImage’,
‘downloadImage’,
‘getNetworkType’,
‘openLocation’,
‘getLocation’,
‘hideOptionMenu’,
‘showOptionMenu’,
‘closeWindow’,
‘scanQRCode’,
‘chooseWXPay’,
‘openProductSpecificView’,
‘addCard’,
‘chooseCard’,
‘openCard’
] /* 必填,需要使用的JS接口列表,所有JS接口列表見附錄2*/
});}
})
.error(function (data, header, config, status) {//處理響應失敗
// 當ajax請求出現錯誤時,顯示一個提示信息
$ionicLoading.show({
animation: ‘fade-in’,
showBackdrop: false,
template: “網絡延遲,請重新嘗試”,
duration: 3000
});
});}
//請求接口,獲取微信JSSDK參數==end===
2、會員頭像的讀取和上傳。
這個地方對比兩個代碼就明白了,不是使用File控件,而是調用公眾號的文件讀取和上傳接口,調用這些接口的好處在于可以自動壓縮上傳的圖片。
Cordova下的代碼:
buttonClicked: function (index) {
if (index == 0) {
//type = ‘camera’;
var srcType = Camera.PictureSourceType.CAMERA;
} else if (index == 1) {
//type = ‘gallery’;
var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
}
var options = setOptions(srcType);
//var func = createNewFileEntry;options.targetHeight = 1200;
options.targetWidth = 1200;
navigator.camera.getPicture(function cameraSuccess(imageUri) {
console.log(imageUri);
$scope.temp_image = imageUri;
$scope.head_logo = imageUri;
//$scope.uoload_img();//彈出緩沖提示
$scope.showLoadingToast();
//這里使用定時器是為了緩存一下加載過程,防止加載過快
$timeout(function () {
//停止緩沖提示
$scope.hideLoadingToast();
}, 1000);
}, function cameraError(error) {
console.debug(“Unable to obtain picture: ” + error, “app”);//顯示等待
//彈出緩沖提示
$scope.showLoadingToast();
//這里使用定時器是為了緩存一下加載過程,防止加載過快
$timeout(function () {
//停止緩沖提示
$scope.hideLoadingToast();
}, 2500);
}, options);}
});
$timeout(function () {
hideSheet();
}, 3000);
公眾號中的代碼:
$scope.choosePicMenu = function () {
wx.chooseImage({
count: 1, // 默認9
sizeType: [‘original’, ‘compressed’], // 可以指定是原圖還是壓縮圖,默認二者都有
sourceType: [‘album’, ‘camera’], // 可以指定來源是相冊還是相機,默認二者都有
success: function (res) {
var localIds = res.localIds; // 返回選定照片的本地ID列表,localId可以作為img標簽的src屬性顯示圖片wx.uploadImage({
localId: localIds[0], // 需要上傳的圖片的本地ID,由chooseImage接口獲得
isShowProgressTips: 1, // 默認為1,顯示進度提示
success: function (res) {
var serverId = res.serverId; // 返回圖片的服務器端ID$http({
method: ‘post’,//請求方式
url: http_server + “/index.php?g=Yanyubao&m=Kuaicar&a=get_image_url_by_weixin_media_id”,//請求地址
data: {‘serverId’: serverId}//請求參數,如果使用JSON格式的對象則可為 data: JSON.stringify(obj),
//timeout: 8000//請求等待時間
})
.success(function (data) {
if (data.code == ‘1’) {
console.log(2222222222);
console.log(data);
console.log(2222222222);
$scope.head_logo = data.url2;//$ionicLoading.hide();
}
})
.error(function (data, header, config, status) {
//處理響應失敗
// 當ajax請求出現錯誤時,顯示一個提示信息
$ionicLoading.show({
animation: ‘fade-in’,
showBackdrop: false,
template: “網絡延遲,請重新嘗試”,
duration: 3000
});
})}
});}
});}
3、用戶GPS坐標(經緯度)的讀取。
由于國內的地圖中GPS坐標是加密的,因此獲取微信信息,調用百度地圖的接口是穩定的。
///讀取gps經緯度信息
$scope.getGeolocation = function () {if(is_in_cordova_browser){
// 使用百度地圖插件進行定位
baidumap_location.getCurrentPosition(function (result) {
console.log(JSON.stringify(result, null, 4));
//alert(JSON.stringify(result, null, 4));$scope.latitude = result.latitude;//緯度
$scope.longitude = result.longitude;//經度
console.log(‘緯度:’ + $scope.latitude + ‘經度:’ + $scope.longitude);$scope.get_machine_list();
}, function (error) {
console.log(‘調用百度地圖插件失敗:’+error);
alert(‘調用地圖失敗:’+error);
});}else if(is_in_weixin_browser && !is_in_wxa_browser ){
navigator.geolocation.getCurrentPosition(updataPosiyion);}
}function updataPosiyion(position){
var latitudeP = position.coords.latitude;
var longitudeP = position.coords.longitude;var point = new BMap.Point(longitudeP,latitudeP);
$scope.latitude = point.lat;//緯度
$scope.longitude = point.lng;//經度
console.log(‘緯度:’ + $scope.latitude + ‘經度:’ + $scope.longitude);$scope.get_machine_list();
}
});
4、二維碼掃描控件的調用。
使用公眾號的二維碼掃描接口,其實比使用Cordova插件的二維碼掃碼功能簡單多了,而且用戶體驗更好。
if(is_in_cordova_browser){
/////調掃碼插件
cordova.plugins.barcodeScanner.scan(
function (result) {
var machine_url = result.text;
console.log(‘洗車機機器url’ + machine_url);
var machineurl=encodeURI(machine_url);$scope.check_machine(machineurl);
},
function (error) {
console.log(“Scanning failed: ” + error);
}
);
}else if(is_in_weixin_browser && !is_in_wxa_browser){
//alert(11111111);
wx.scanQRCode({needResult: 1, // 默認為0,掃描結果由微信處理,1則直接返回掃描結果,
scanType: [“qrCode”,”barCode”], // 可以指定掃二維碼還是一維碼,默認二者都有
success: function (res) {
var result = res.resultStr; // 當needResult 為 1 時,掃碼返回的結果
//console.log(‘掃碼結果:’+result);
//alert(result);
var machineurl=encodeURI(result);$scope.check_machine(machineurl);
}
});
}
5、微信支付收款接口的調用。
這里調用的肯定是微信的公眾號,而不是H5收款接口,首先參考第一點,獲取當前的用戶的openid,在調用微信支付APP接口的地方做判斷,調用對應的公眾號內支付接口。
首先需要隱藏支付寶收款,畢竟是在公眾號里面。
//在微信環境隱藏支付寶支付
$scope.is_in_weixin_browser = is_in_weixin_browser;
原生微信支付接口調用:
//微信APP支付
$scope.wechat_pay = function(payInfo,orderid,payment_type){
// console.table(payInfo);
//payInfo = JSON.parse(payInfo);
//console.log(payInfo.sub_mch_id);// alert(JSON.stringify(payInfo));
var params = {
partnerid: payInfo.partnerid, // merchant id
prepayid: payInfo.prepayid, // prepay id
noncestr: payInfo.noncestr, // nonce
timestamp: payInfo.timestamp, // timestamp
sign: payInfo.sign, // signed string
};
console.log(params.partnerid);
console.log(params.prepayid);
console.log(params.noncestr);
console.log(params.timestamp);
console.log(params.sign);// alert(JSON.stringify(params));
Wechat.sendPaymentRequest(params, function () {
// alert(“Success”);
$scope.order_buy_result(orderid,payment_type);
// alert(“回調成功”);
var alertPopup = $ionicPopup.alert({
title: ‘友情提示’,
template: “<p style=’text-align: center’>支付完成</p>”,
okText: ‘確定’, // String (默認: ‘OK’)。OK按鈕的文字。
okType: ‘button-assertive’, // String (默認: ‘button-positive’)。OK按鈕的類型。
});
alertPopup.then(function(res) {
//跳轉到支付成功頁面$state.go(“pay_success”, {‘orderid’:orderid}, {reload:true});
return false;
});}, function (reason) {
//alert(“reason=>”+reason);var alertPopup = $ionicPopup.alert({
title: ‘友情提示’,
template: “<p style=’text-align: center’>”+reason+”</p>”,
okText: ‘確定’, // String (默認: ‘OK’)。OK按鈕的文字。
okType: ‘button-assertive’, // String (默認: ‘button-positive’)。OK按鈕的類型。
});console.log(“Failed: ” + reason);
});}
公眾號支付的代碼:
//微信公眾號支付
$scope.wechat_pay_jsapi = function(payInfo,openid){
// console.log(2233244);
// console.log(payInfo);
// console.log(2233244);
//payInfo = JSON.parse(payInfo);
//console.log(payInfo.sub_mch_id);//var prepayid = payInfo.prepay_id; // prepay id
//var appid = payInfo.appid; //appid
var parameters = encodeURIComponent(payInfo.parameters); //appid//alert( weixin_payment_failure);
var jump_to_url = encodeURIComponent(weixin_payment_success);
var jump_url_failure = encodeURIComponent(weixin_payment_failure);var pay_url = weixin_payment_dir;
pay_url += ‘?parameters=’+ parameters + ‘&jump_to_url=’ + jump_to_url + ‘&jump_url_failure=’ + jump_url_failure ;
// console.log(123);
// console.log(pay_url);
// console.log(123);
//alert(pay_url);
window.location= pay_url;}
公眾號收款首先要獲取當前粉絲的openid,對應的接口調用代碼:
//
$scope.check_openid_cache = function (){
var o_weixin_openid = localStorage.getItem(“o_weixin_openid”);
//alert(‘o_weixin_openid:’+o_weixin_openid);
//alert(encodeURIComponent(document.location.href));if (!o_weixin_openid ) {
//alert(‘o_weixin_openid == undefined’);
location.href = http_server + “/index.php?g=Yanyubao&m=ShopApp&a=weixin_oauthor&sellerid=”+ sellerid +”&returl=”+encodeURIComponent(document.location.href);
return;
}
//alert(‘222222’);return o_weixin_openid;
}$scope.get_openid_from_server = function () {
//檢查是否要從服務器獲取openid
var weixin_openid_token = $location.search().weixin_openid_token;//alert(‘weixin_openid_token:’+weixin_openid_token);
//alert(window.location.href);
//alert(“get from url, openid token:”+weixin_openid_token);if (weixin_openid_token) {
alert(‘ready to get weixin_get_openid’);//同步ajax請求
$http({method: ‘post’,//請求方式
url:http_server + “/index.php?g=Yanyubao&m=ShopApp&a=weixin_get_openid”,//請求地址data: {“weixin_openid_token” : weixin_openid_token} //請求參數,如果使用JSON格式的對象則可為 data: JSON.stringify(obj),
})
.success(function (res) {
//alert(‘success:’+res);window.localStorage.setItem(“o_weixin_openid”, res.openid);
})
.error(function (res, header, config, status) {//處理響應失敗
// 當ajax請求出現錯誤時,顯示一個提示信息
$ionicLoading.show({
animation: ‘fade-in’,
showBackdrop: false,
template: “網絡延遲,請重新嘗試”,
duration: 3000
});
});}
else{
console.log(‘$scope.check_openid_cache()’);
//alert(2888888);
$scope.check_openid_cache();}
}
通過對以上接口的兼容性改造,Cordova項目實現了對微信公眾號的兼容。最后再討論一個基礎的問題,即如何判斷公眾號環境還是Cordova環境。這個問題的解決方案來自對User Agent的判斷。Cordova環境的UA可以自己定義,這個可以在config.xml中指定,根據這個字符串可以判斷。在微信瀏覽器中,UA是帶有字符串“MicroMessenger”的,但是需要同時判斷是否在小程序的瀏覽器中,需要引用:
https://res.wx.qq.com/open/js/jweixin-1.3.2.js
這個判斷在小程序的官方文檔中也有說明,因為小程序瀏覽器中是不能調用公眾號的接口。