微信小程序 openid及支付的若干问题解决方案 您所在的位置:网站首页 小程序显示openid是必传的 微信小程序 openid及支付的若干问题解决方案

微信小程序 openid及支付的若干问题解决方案

2024-05-21 17:05| 来源: 网络整理| 查看: 265

 

微信小程序API帮助文档中介绍

wx.login(OBJECT)

调用接口获取登录凭证(code)进而换取用户登录态信息,包括用户的唯一标识(openid) 及本次登录的 会话密钥(session_key)等。用户数据的加解密通讯需要依赖会话密钥完成。

登录时序图

(1)通过调用login方法可以从微信服务器获取code

1 wx.login({ 2 success: function(res) { 3 if (res.code) { 4 //发起网络请求 5 wx.request({ 6 url: 'https://test.com/onLogin', 7 data: { 8 code: res.code 9 } 10 }) 11 } else { 12 console.log('获取用户登录态失败!' + res.errMsg) 13 } 14 } 15 }); 1 wx.request({ 2 url: 'https://×××××', 3 data: { 4 js_code: jscode 5 }, 6 method: 'POST', 7 header: { 'content-type': 'application/x-www-form-urlencoded' }, // 设置请求的 header 8 success: function (res) { 9 app.globalData.openid = res.data['openid']; 10 console.log("res.data.openid=" + res.data['openid']); 11 console.log("app.globalData.openid =" + app.globalData.openid ); 12 } 13 });

 

(2)把code提交到自己的服务器,并通过微信服务器对code进行验证

https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code服务器端接收验证代码 1 function getOpenidAction() { 2 3 $js_code= $_POST['js_code']; 4 //echo 'js_code=' .$js_code; 5 $appid = '小程序ID'; 6 $appsecret = '小程序的密钥'; 7 $access_url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$js_code."&grant_type=authorization_code"; 8 $str = $this->https_request($access_url); 9 print_r($str); 10 } 11 12 13 //发起https请求 14 function https_request($url) 15 { 16 $curl = curl_init(); 17 curl_setopt($curl, CURLOPT_URL, $url); 18 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); 19 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); 20 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 21 curl_setopt($curl, CURLOPT_TIMEOUT, 500); 22 $data = curl_exec($curl); 23 if (curl_errno($curl)){ 24 return 'ERROR'; 25 } 26 curl_close($curl); 27 return $data; 28 }

最后开发者服务器使用登录凭证 code 获取 session_key 和 openid。

 

 

二、微信小程序支付

通过返回的openid,对requestpayment方法进行组装

1 wx.request({ 2 url: 'https://你的域名/wp-wxpay/pay/app.php', 3 data: { 4 //全局变量 5 openid: app.globalData.openid, 6 //定义支付金额 7 total_fee: total_fee 8 }, 9 header: { 'content-type': 'application/x-www-form-urlencoded' }, // 设置请求的 header 10 method: 'POST', 11 success: function (res) { 12 var temp = res.data; 13 console.log("timestamp = " + temp); 14 //调用支付方法,整合参数后,提交到服务器验证审核 15 wx.requestPayment({ 16 'timeStamp': res.data.timeStamp, 17 'nonceStr': res.data.nonceStr, 18 'package': res.data.package, 19 'signType': 'MD5', 20 'paySign': res.data.paySign, 21 'success': function (res) { 22 }, 23 'fail': function (res) { 24 wx.showToast({ 25 title: '报名失败!', 26 icon: 'success' 27 }); 28 }, 29 complete: function (res) { 30 if (res.errMsg == 'requestPayment:fail cancel') { 31 wx.showToast({ 32 title: '取消报名', 33 icon: 'success' 34 }); 35 } 36 37 } 38 }); 39 }, 40 41 }); 后端代码:

1. pay.php //小程序请求的后端地址

1


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有