这个问题我相信很多人都碰到过,我也不另外。遇到这个问题的时候,也上网搜索过,可惜,网上的答案都是千篇一律,没办法我只能仔细研究官方文档。最终,让我搞定了这个问题。各位网友,只要你按照我的步骤走下去,100%包你过。我们先看一张效果图:
下面我先从后端为大家讲解,原理我就不说了,大家自己看官网。由于我的后端用的是PHP,因此使用的是thinkphp5来实现这个功能,不懂thinkphp5的朋友可以去网上恶补一下,后期我会单独推出hinkphp5开发视频,我会尽最大努力能让大家看懂。在这里需要重点说明一下,一定要把小程序与微信公众号绑定在一起。这个可以通过微信公众号内“绑定小程序”功能来实现。
一、获取access_token
public function getAccessToken() {
$appId = '微信公众号的APPID'; //注意,这里不是微信小程序的APPID
$secret = '微信公众号的secret'; //注意,这里也不是微信小程序的secret
/*以上两个参数,是在微信公众号的基本配置里面查看
注意:这个accesstoken一定要缓存起来,因为它有时效性(7200秒)
*/
$access_token = Catch::get('access_token');
if ($access_token) {
return $access_token;
} else {
$timeout = 5;
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=" . secret;
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
//获取access_token和openid,转换为数组
$access = json_decode(curl_exec($curl),true);
Cache::set('access_token', $access['access_token'], 7200);
return $access['access_token'];
}
}
二、获取卡券的ticket
/**
* 获取卡券ticket
* @return mixed|string
*/
public function getCardApiTicket() {
$api_ticket = Cache::get('card_api_ticket');
if ($api_ticket) {
return $api_ticket;
} else {
$token = $this->getAccess_token(); //上一步得到的access_token
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $token . "&type=wx_card";
$api_ticket = $this->request_Get($url);
$res = json_decode($api_ticket, true);
Cache::get('card_api_ticket',$res['ticket'],7200);
return $res['ticket'];
}
}
/***
* GET方法
* @param $url
* @return mixed
*/
public function request_Get($url){
$curl = curl_init();
$timeout = 5;
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
$tmpInfo = curl_exec($curl); //返回api的json对象
//关闭URL请求
curl_close($curl);
return $tmpInfo; //返回json对象
}
三、卡券签名
这一步是非常关键的一步,很多人都是在这里栽跟头的。为了不让大家走弯路,我会详细说明。根据官网的要求,我们添加卡券的时候需要提供卡券ID,时间戳,签名,这里最难的一个就是签名,根据我本人的多次调试,终于找到了一劳永逸的方法。代码如下:
/**
* 获取卡券签名
* @param $timestamp int 时间戳
* @param $api_ticket string 卡券ticket
* @param $noncestr string 随机字符串,由开发者设置传入,加强安全性(若不填写可能被重放请求)。随机字符串,不长于 32 位
* @param $card_id string 卡券ID
* @param $openid string 用户的微信小程序openid
* @param $code string 卡的编号
* @return array
*/
public function cardSignature($timestamp, $api_ticket, $noncestr, $card_id, $openid, $code){
$arr = array();
$arr['timestamp'] = $timestamp;
$arr['code'] = $code;
$arr['nonce_str'] = $noncestr;
$arr['ticket'] = $api_ticket;
$arr['openid'] = $openid;
$arr['card_id'] = $card_id;
//根据官网说明,卡券签名需要的参数有:timestamp(时间戳),code(卡的编号),nonce_str(随机字符串),ticket(卡券ticket),openid(用户的openid),card_id(卡券的ID)
sort($arr, SORT_STRING); //排序,这一步一定要有,否则会不成功
$str = '';
foreach ($arr as $v) {
$str .= $v;
}
//通过foreach组装成字符串
$signature = sha1($str); //最后通过sha1生成签名
return array('code' => $code,'openid' =>$openid,'timestamp'=>$timestamp,'nonce_str'=>$noncestr,'signature'=>$signature);
}
四、获取卡券
/**
* 获取用户卡券
* @return mixed
*/
public function getUserCard() {
$openid = input('openid'); //前端传的参数
$token = $this->getAccess_token(); //这里就是之前获取的access_token
$url = "https://api.weixin.qq.com/card/user/getcardlist?access_token=" . $token; //调用接口凭证
$data = array();
$data['openid'] = $openid;
$dataRes = $this->request_post($url, json_encode($data));
$res = json_decode($dataRes,true);
if ($res['errcode'] == 0) {
//成功
$list = array();
$timestamp = time(); //时间戳
$card_ticket = $this->getCardApiTicket(); //获取卡券API_ticket
$nonce_str = $this->generateNonceStr(); //随机字符串
foreach ($res['card_list'] as $k => $val) {
$result = $this->cardSignature($timestamp,$card_ticket,$nonce_str,$val['card_id'],$openid,$val['code']);
$list['cardId'] = $val['card_id'];
$list['cardExt'] = json_encode($result);
}
return $this->resMap(200, $list, $list);
} else {
return $this->resMap(4002,'暂时没有数据','暂时没有数据');
}
}
/**
* 发送post请求
* @param string $url
* @param string $param
* @return bool|mixed
*/
public function request_post($url = '', $param = '')
{
if (empty($url) || empty($param)) {
return false;
}
$postUrl = $url;
$curlPost = $param;
$ch = curl_init(); //初始化curl
curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec($ch); //运行curl
curl_close($ch);
return $data;
}
/**
* 密码字符集
* @param int $length
* @return string
*/
public function generateNonceStr($length=16){
// 密码字符集,可任意添加你需要的字符
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for($i = 0; $i < $length; $i++)
{
$str .= $chars[mt_rand(0, strlen($chars) - 1)];
}
return $str;
}
/**
* 返回提示信息
* @param $code string 错误码 4001 空值 4002 格式不正确 4003 长度 4004 提示 200正确放回 ,0失败
* @param $msg string 错误描述
* @param $data string 返回值
* @return array
*/
public function resMap($code, $msg, $data)
{
$map = array();
$map['errMsg'] = $msg;
$map['data'] = $data;
$map['errCode'] = $code;
return json($map);
}
以上就是后端的核心代码,下面我们把上面的代码重新整理在一个页面上。
namespace app\rest\controller;
use think\Controller;
use think\Cache;
use think\Log;
//类名为Card
class Card extends Controller {
/**
获取access_token
*/
public function getAccessToken() {
$appId = '微信公众号的APPID'; //注意,这里不是微信小程序的APPID
$secret = '微信公众号的secret'; //注意,这里也不是微信小程序的secret
/*以上两个参数,是在微信公众号的基本配置里面查看
注意:这个accesstoken一定要缓存起来,因为它有时效性(7200秒)
*/
$access_token = Catch::get('access_token');
if ($access_token) {
return $access_token;
} else {
$timeout = 5;
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=" . secret;
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
//获取access_token和openid,转换为数组
$access = json_decode(curl_exec($curl),true);
Cache::set('access_token', $access['access_token'], 7200);
return $access['access_token'];
}
}
/**
* 获取卡券ticket
* @return mixed|string
*/
public function getCardApiTicket() {
$api_ticket = Cache::get('card_api_ticket');
if ($api_ticket) {
return $api_ticket;
} else {
$token = $this->getAccess_token(); //上一步得到的access_token
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $token . "&type=wx_card";
$api_ticket = $this->request_Get($url);
$res = json_decode($api_ticket, true);
Cache::get('card_api_ticket',$res['ticket'],7200);
return $res['ticket'];
}
}
/***
* GET方法
* @param $url
* @return mixed
*/
public function request_Get($url){
$curl = curl_init();
$timeout = 5;
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
$tmpInfo = curl_exec($curl); //返回api的json对象
//关闭URL请求
curl_close($curl);
return $tmpInfo; //返回json对象
}
/**
* 获取卡券签名
* @param $timestamp int 时间戳
* @param $api_ticket string 卡券ticket
* @param $noncestr string 随机字符串,由开发者设置传入,加强安全性(若不填写可能被重放请求)。随机字符串,不长于 32 位
* @param $card_id string 卡券ID
* @param $openid string 用户的微信小程序openid
* @param $code string 卡的编号
* @return array
*/
public function cardSignature($timestamp, $api_ticket, $noncestr, $card_id, $openid, $code){
$arr = array();
$arr['timestamp'] = $timestamp;
$arr['code'] = $code;
$arr['nonce_str'] = $noncestr;
$arr['ticket'] = $api_ticket;
$arr['openid'] = $openid;
$arr['card_id'] = $card_id;
//根据官网说明,卡券签名需要的参数有:timestamp(时间戳),code(卡的编号),nonce_str(随机字符串),ticket(卡券ticket),openid(用户的openid),card_id(卡券的ID)
sort($arr, SORT_STRING); //排序,这一步一定要有,否则会不成功
$str = '';
foreach ($arr as $v) {
$str .= $v;
}
//通过foreach组装成字符串
$signature = sha1($str); //最后通过sha1生成签名
return array('code' => $code,'openid' =>$openid,'timestamp'=>$timestamp,'nonce_str'=>$noncestr,'signature'=>$signature);
}
/**
* 获取用户卡券
* @return mixed
*/
public function getUserCard() {
$openid = input('openid'); //前端传的参数
$token = $this->getAccess_token(); //这里就是之前获取的access_token
$url = "https://api.weixin.qq.com/card/user/getcardlist?access_token=" . $token; //调用接口凭证
$data = array();
$data['openid'] = $openid;
$dataRes = $this->request_post($url, json_encode($data));
$res = json_decode($dataRes,true);
if ($res['errcode'] == 0) {
//成功
$list = array();
$timestamp = time(); //时间戳
$card_ticket = $this->getCardApiTicket(); //获取卡券API_ticket
$nonce_str = $this->generateNonceStr(); //随机字符串
foreach ($res['card_list'] as $k => $val) {
$result = $this->cardSignature($timestamp,$card_ticket,$nonce_str,$val['card_id'],$openid,$val['code']);
$list['cardId'] = $val['card_id'];
$list['cardExt'] = json_encode($result);
}
return $this->resMap(200, $list, $list);
} else {
return $this->resMap(4002,'暂时没有数据','暂时没有数据');
}
}
/**
* 发送post请求
* @param string $url
* @param string $param
* @return bool|mixed
*/
public function request_post($url = '', $param = '')
{
if (empty($url) || empty($param)) {
return false;
}
$postUrl = $url;
$curlPost = $param;
$ch = curl_init(); //初始化curl
curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec($ch); //运行curl
curl_close($ch);
return $data;
}
/**
* 密码字符集
* @param int $length
* @return string
*/
public function generateNonceStr($length=16){
// 密码字符集,可任意添加你需要的字符
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for($i = 0; $i < $length; $i++)
{
$str .= $chars[mt_rand(0, strlen($chars) - 1)];
}
return $str;
}
/**
* 返回提示信息
* @param $code string 错误码 4001 空值 4002 格式不正确 4003 长度 4004 提示 200正确放回 ,0失败
* @param $msg string 错误描述
* @param $data string 返回值
* @return array
*/
public function resMap($code, $msg, $data)
{
$map = array();
$map['errMsg'] = $msg;
$map['data'] = $data;
$map['errCode'] = $code;
return json($map);
}
}
前端如何使用
一、获取用户的openid
这里我们可以通过wx.login()方法获取,参考地址:https://developers.weixin.qq.com/miniprogram/dev/api/api-login.html,然后把openid作为一个参数传递给后端。在这里我插一句,要想获取用户的openid,我们需要通过wx.login方法往后退传递code参数,通过这个参数我们才能获取openid,如何操作,我们会在下一章节详细讲解。包括建表、后端、前端等知识。
这里假设我们已经有了openid,那么我们就通过这个openid获取卡券,我把代码写在index.js里面,具体位置为onload:function();代码如下:
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let that = this;
let openid = userInfo.m_openid;
wx.request({
url: 'https://xxx.com/rest/Card/getUserCard', //仅为示例,并非真实的接口地址
method: 'POST', //POST一定要大写
data: {
openid: openid,
},
header: {
'content-type': 'application/json' // 默认值
},
success: function(res) {
if (res.errCode == 200) {
//wx.addCard也就是微信小程序的API,地址:https://developers.weixin.qq.com/miniprogram/dev/api/card.html#wxaddcardobject
wx.addCard({
cardList: [res.errMsg],
success: function(rs) {
console.log(rs) // 卡券添加结果
}
})
} else {
// wx.showModal 弹窗
wx.showModal({
title: '提示',
content: res.errMsg,
showCancel: false,
success: function(res) {
console.log(res);
}
})
}
}
})
},
以上就是解决签名错误的详细方案,希望对大家有用,谢谢!