关键字:微信公众平台 JSSDK 发送给朋友 收货地址共享接口 openAddress
作者:方倍工作室
原文:http://www.cnblogs.com/txw1958/p/weixin-openaddress.html
在这篇微信公众平台开发教程中,我们将介绍如何在网页中实现获取收货地址的功能。
收货地址共享接口 在2016年4月13日 进行过升级,2016年5月20日只能使用新接口,本教程为新版接口的教程!
本文分为以下二个部分:
access token的获得方法在前面有介绍,详情见 微信公众平台开发(26) ACCESS TOKEN
生成签名之前必须先了解一下jsapi_ticket,jsapi_ticket是公众号用于调用微信JS接口的临时票据。正常情况下,jsapi_ticket的有效期为7200秒,通过access_token来获取。由于获取jsapi_ticket的api调用次数非常有限,频繁刷新jsapi_ticket会导致api调用受限,影响自身业务,开发者必须在自己的服务全局缓存jsapi_ticket 。
参考以下文档获取access_token(有效期7200秒,开发者必须在自己的服务全局缓存access_token):
用第一步拿到的access_token 采用http GET方式请求获得jsapi_ticket(有效期7200秒,开发者必须在自己的服务全局缓存jsapi_ticket),接口地址如下
https:<span>//</span><span>api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi</span>
成功返回如下JSON:
<span>{ </span><span>"</span><span>errcode</span><span>"</span>:<span>0</span><span>, </span><span>"</span><span>errmsg</span><span>"</span>:<span>"</span><span>ok</span><span>"</span><span>, </span><span>"</span><span>ticket</span><span>"</span>:<span>"</span><span>bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA</span><span>"</span><span>, </span><span>"</span><span>expires_in</span><span>"</span>:<span>7200</span><span> }</span>
获得jsapi_ticket之后,就可以生成JS-SDK权限验证的签名了。
签名生成规则如下:参与签名的字段包括noncestr(随机字符串), 有效的jsapi_ticket, timestamp(时间戳), url(当前网页的URL,不包含#及其后面部分) 。对所有待签名参数按照字段名的ASCII 码从小到大排序(字典序)后,使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串string1。这里需要注意的是所有参数名均为小写字符。对string1作sha1加密,字段名和字段值都采用原始值,不进行URL 转义。
即signature=sha1(string1)。 示例:
noncestr=<span>Wm3WZYTPz0wzccnW jsapi_ticket</span>=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-<span>HhTdfl2fzFy1AOcHKP7qg timestamp</span>=<span>1414587457</span><span> url</span>=http:<span>//</span><span>mp.weixin.qq.com?params=value</span>
步骤1. 对所有待签名参数按照字段名的ASCII 码从小到大排序(字典序)后,使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串string1:
jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW×tamp=<span>1414587457</span>&url=http:<span>//</span><span>mp.weixin.qq.com?params=value</span>
步骤2. 对string1进行sha1签名,得到signature:
0f9de62fce790f9a083d5c99e95740ceb90c27ed
完整代码如下
<?<span>php </span><span>class</span><span> JSSDK { </span><span>private</span> <span>$appId</span><span>; </span><span>private</span> <span>$appSecret</span><span>; </span><span>public</span> <span>function</span> __construct(<span>$appId</span>, <span>$appSecret</span><span>) { </span><span>$this</span>->appId = <span>$appId</span><span>; </span><span>$this</span>->appSecret = <span>$appSecret</span><span>; } </span><span>public</span> <span>function</span><span> getSignPackage() { </span><span>$jsapiTicket</span> = <span>$this</span>-><span>getJsApiTicket(); </span><span>//</span><span> 注意 URL 一定要动态获取,不能 hardcode.</span> <span>$protocol</span> = (!<span>empty</span>(<span>$_SERVER</span>['HTTPS']) && <span>$_SERVER</span>['HTTPS'] !== 'off' || <span>$_SERVER</span>['SERVER_PORT'] == 443) ? "https://" : "http://"<span>; </span><span>$url</span> = "<span>$protocol$_SERVER</span>[HTTP_HOST]<span>$_SERVER</span>[REQUEST_URI]"<span>; </span><span>$timestamp</span> = <span>time</span><span>(); </span><span>$nonceStr</span> = <span>$this</span>-><span>createNonceStr(); </span><span>//</span><span> 这里参数的顺序要按照 key 值 ASCII 码升序排序</span> <span>$string</span> = "jsapi_ticket=<span>$jsapiTicket</span>&noncestr=<span>$nonceStr</span>×tamp=<span>$timestamp</span>&url=<span>$url</span>"<span>; </span><span>$signature</span> = <span>sha1</span>(<span>$string</span><span>); </span><span>$signPackage</span> = <span>array</span><span>( </span>"appId" => <span>$this</span>->appId, "nonceStr" => <span>$nonceStr</span>, "timestamp" => <span>$timestamp</span>, "url" => <span>$url</span>, "signature" => <span>$signature</span>, "rawString" => <span>$string</span><span> ); </span><span>return</span> <span>$signPackage</span><span>; } </span><span>private</span> <span>function</span> createNonceStr(<span>$length</span> = 16<span>) { </span><span>$chars</span> = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"<span>; </span><span>$str</span> = ""<span>; </span><span>for</span> (<span>$i</span> = 0; <span>$i</span> < <span>$length</span>; <span>$i</span>++<span>) { </span><span>$str</span> .= <span>substr</span>(<span>$chars</span>, <span>mt_rand</span>(0, <span>strlen</span>(<span>$chars</span>) - 1), 1<span>); } </span><span>return</span> <span>$str</span><span>; } </span><span>private</span> <span>function</span><span> getJsApiTicket() { </span><span>//</span><span> jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例</span> <span>$data</span> = json_decode(<span>file_get_contents</span>("jsapi_ticket.json"<span>)); </span><span>if</span> (<span>$data</span>->expire_time < <span>time</span><span>()) { </span><span>$accessToken</span> = <span>$this</span>-><span>getAccessToken(); </span><span>//</span><span> 如果是企业号用以下 URL 获取 ticket // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";</span> <span>$url</span> = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=<span>$accessToken</span>"<span>; </span><span>$res</span> = json_decode(<span>$this</span>->httpGet(<span>$url</span><span>)); </span><span>$ticket</span> = <span>$res</span>-><span>ticket; </span><span>if</span> (<span>$ticket</span><span>) { </span><span>$data</span>->expire_time = <span>time</span>() + 7000<span>; </span><span>$data</span>->jsapi_ticket = <span>$ticket</span><span>; </span><span>$fp</span> = <span>fopen</span>("jsapi_ticket.json", "w"<span>); </span><span>fwrite</span>(<span>$fp</span>, json_encode(<span>$data</span><span>)); </span><span>fclose</span>(<span>$fp</span><span>); } } </span><span>else</span><span> { </span><span>$ticket</span> = <span>$data</span>-><span>jsapi_ticket; } </span><span>return</span> <span>$ticket</span><span>; } </span><span>private</span> <span>function</span><span> getAccessToken() { </span><span>//</span><span> access_token 应该全局存储与更新,以下代码以写入到文件中做示例</span> <span>$data</span> = json_decode(<span>file_get_contents</span>("access_token.json"<span>)); </span><span>if</span> (<span>$data</span>->expire_time < <span>time</span><span>()) { </span><span>//</span><span> 如果是企业号用以下URL获取access_token // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";</span> <span>$url</span> = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=<span>$this</span>->appId&secret=<span>$this</span>->appSecret"<span>; </span><span>$res</span> = json_decode(<span>$this</span>->httpGet(<span>$url</span><span>)); </span><span>$access_token</span> = <span>$res</span>-><span>access_token; </span><span>if</span> (<span>$access_token</span><span>) { </span><span>$data</span>->expire_time = <span>time</span>() + 7000<span>; </span><span>$data</span>->access_token = <span>$access_token</span><span>; </span><span>$fp</span> = <span>fopen</span>("access_token.json", "w"<span>); </span><span>fwrite</span>(<span>$fp</span>, json_encode(<span>$data</span><span>)); </span><span>fclose</span>(<span>$fp</span><span>); } } </span><span>else</span><span> { </span><span>$access_token</span> = <span>$data</span>-><span>access_token; } </span><span>return</span> <span>$access_token</span><span>; } </span><span>private</span> <span>function</span> httpGet(<span>$url</span><span>) { </span><span>$curl</span> =<span> curl_init(); curl_setopt(</span><span>$curl</span>, CURLOPT_RETURNTRANSFER, <span>true</span><span>); curl_setopt(</span><span>$curl</span>, CURLOPT_TIMEOUT, 500<span>); curl_setopt(</span><span>$curl</span>, CURLOPT_SSL_VERIFYPEER, <span>false</span><span>); curl_setopt(</span><span>$curl</span>, CURLOPT_SSL_VERIFYHOST, <span>false</span><span>); curl_setopt(</span><span>$curl</span>, CURLOPT_URL, <span>$url</span><span>); </span><span>$res</span> = curl_exec(<span>$curl</span><span>); curl_close(</span><span>$curl</span><span>); </span><span>return</span> <span>$res</span><span>; } }</span>
微信收货地址共享,是指用户在微信浏览器内打开网页,填写过地址后,后续可以免填写支持快速选择,也可增加和编辑。此地址为用户属性,可在各商户的网页中共享使用。支持原生控件填写地址,地址数据会传递到商户。
地址共享是基于微信JavaScript API 实现,只能在微信内置浏览器中使用,其他浏览器调用无效。同时,需要微信5.0 版本才能支持,建议通过user agent 来确定用户当前的版本号后再调用地址接口。以iPhone 版本为例,可以通过useragent可获取如下微信版本示例信息:"Mozilla/5.0(iphone;CPU iphone OS 5_1_1 like Mac OS X)AppleWebKit/534.46(KHTML,like Geocko) Mobile/9B206MicroMessenger/5.0"其中5.0 为用户安装的微信版本号,商户可以判定版本号是否高于或者等于5.0。
地址格式
微信地址共享使用的数据字段包括:
其中,地区对应是国标三级地区码,如“广东省-广州市-天河区”,对应的邮编是是510630。详情参考链接:http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/201401/t20140116_501070.html
先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
<?<span>php </span><span>require_once</span> "jssdk.php"<span>; </span><span>$jssdk</span> = <span>new</span> JSSDK("yourAppID", "yourAppSecret"<span>); </span><span>$signPackage</span> = <span>$jssdk</span>-><span>GetSignPackage(); </span>?>
在需要调用JS接口的页面引入如下JS文件:
特别注意:JS-SDK版本需使用http://res.wx.qq.com/open/js/jweixin-1.1.0.js
<span><</span><span>script </span><span>src</span><span>="http://res.wx.qq.com/open/js/jweixin-1.1.0.js"</span><span>></</span><span>script</span><span>></span>
所有需要使用JS-SDK的页面必须先注入配置信息,否则将无法调用。
<script><span> wx.config({ debug: </span><span>false</span><span>, appId: </span>'<?php echo $signPackage["appId"];?>'<span>, timestamp: </span><?php echo $signPackage["timestamp"];?><span>, nonceStr: </span>'<?php echo $signPackage["nonceStr"];?>'<span>, signature: </span>'<?php echo $signPackage["signature"];?>'<span>, jsApiList: [ </span><span>//</span><span> 所有要调用的 API 都要加到这个列表中</span> 'checkJsApi'<span>, </span>'openAddress'<span>, ] }); </span></script>
5. 通过ready接口处理成功验证
需要在页面加载时就调用,需要把相关接口放在ready函数中调用来确保正确执行
wx.ready(<span>function</span><span> () { });</span>
5.1 通过checkJsApi判断当前客户端版本是否支持分享参数自定义
<span> wx.checkJsApi({ jsApiList: [ </span>'openAddress'<span>, ], success: </span><span>function</span><span> (res) { alert(JSON.stringify(res)); } });</span>
5.3. 实现收货地址共享
<span> wx.openAddress({ trigger: </span><span>function</span><span> (res) { alert(</span>'用户开始拉出地址'<span>); }, success: </span><span>function</span><span> (res) { alert(</span>'用户成功拉出地址'<span>); alert(JSON.stringify(res)); document.form1.address1.value </span>=<span> res.provinceName; document.form1.address2.value </span>=<span> res.cityName; document.form1.address3.value </span>=<span> res.countryName; document.form1.detail.value </span>=<span> res.detailInfo; document.form1.national.value </span>=<span> res.nationalCode; document.form1.user.value </span>=<span> res.userName; document.form1.phone.value </span>=<span> res.telNumber; document.form1.postcode.value </span>=<span> res.postalCode; document.form1.errmsg.value </span>=<span> res.errMsg; document.form1.qq.value </span>= 1354386063<span>; }, cancel: </span><span>function</span><span> (res) { alert(</span>'用户取消拉出地址'<span>); }, fail: </span><span>function</span><span> (res) { alert(JSON.stringify(res)); } });</span>
返回说明
返回值 |
说明 |
---|---|
errMsg |
获取编辑收货地址成功返回“openAddress:ok”。 |
userName |
收货人姓名。 |
postalCode |
邮编。 |
provinceName |
国标收货地址第一级地址(省)。 |
cityName |
国标收货地址第二级地址(市)。 |
countryName |
国标收货地址第三级地址(国家)。 |
detailInfo |
详细收货地址信息。 |
nationalCode |
收货地址国家码。 |