Home >Backend Development >PHP Tutorial >微信支付开发(七) 收货地址共享接口V2

微信支付开发(七) 收货地址共享接口V2

WBOY
WBOYOriginal
2016-06-13 12:29:281258browse

微信支付开发(7) 收货地址共享接口V2

关键字:微信公众平台 JSSDK 发送给朋友 收货地址共享接口 openAddress 
作者:方倍工作室 
原文:http://www.cnblogs.com/txw1958/p/weixin-openaddress.html

 

在这篇微信公众平台开发教程中,我们将介绍如何在网页中实现获取收货地址的功能。

收货地址共享接口 在2016年4月13日 进行过升级,2016年5月20日只能使用新接口,本教程为新版接口的教程!

本文分为以下二个部分:

  1. 生成JS-SDK权限验证签名
  2. 实现获取共享收货地址

 

 

一、微信JS-SDK

1. 获得Access Token

access token的获得方法在前面有介绍,详情见 微信公众平台开发(26) ACCESS TOKEN

2. 获取jsapi_ticket

生成签名之前必须先了解一下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 style="color: #008000;">//</span><span style="color: #008000;">api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi</span>

成功返回如下JSON:

<span style="color: #000000;">{    </span><span style="color: #800000;">"</span><span style="color: #800000;">errcode</span><span style="color: #800000;">"</span>:<span style="color: #800080;">0</span><span style="color: #000000;">,    </span><span style="color: #800000;">"</span><span style="color: #800000;">errmsg</span><span style="color: #800000;">"</span>:<span style="color: #800000;">"</span><span style="color: #800000;">ok</span><span style="color: #800000;">"</span><span style="color: #000000;">,    </span><span style="color: #800000;">"</span><span style="color: #800000;">ticket</span><span style="color: #800000;">"</span>:<span style="color: #800000;">"</span><span style="color: #800000;">bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA</span><span style="color: #800000;">"</span><span style="color: #000000;">,    </span><span style="color: #800000;">"</span><span style="color: #800000;">expires_in</span><span style="color: #800000;">"</span>:<span style="color: #800080;">7200</span><span style="color: #000000;">}</span>

获得jsapi_ticket之后,就可以生成JS-SDK权限验证的签名了。

3. 签名算法实现

签名生成规则如下:参与签名的字段包括noncestr(随机字符串), 有效的jsapi_ticket, timestamp(时间戳), url(当前网页的URL,不包含#及其后面部分) 。对所有待签名参数按照字段名的ASCII 码从小到大排序(字典序)后,使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串string1。这里需要注意的是所有参数名均为小写字符。对string1作sha1加密,字段名和字段值都采用原始值,不进行URL 转义。

即signature=sha1(string1)。 示例:

noncestr=<span style="color: #000000;">Wm3WZYTPz0wzccnWjsapi_ticket</span>=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-<span style="color: #000000;">HhTdfl2fzFy1AOcHKP7qgtimestamp</span>=<span style="color: #800080;">1414587457</span><span style="color: #000000;">url</span>=http:<span style="color: #008000;">//</span><span style="color: #008000;">mp.weixin.qq.com?params=value</span>

步骤1. 对所有待签名参数按照字段名的ASCII 码从小到大排序(字典序)后,使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串string1:

jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW&timestamp=<span style="color: #800080;">1414587457</span>&url=http:<span style="color: #008000;">//</span><span style="color: #008000;">mp.weixin.qq.com?params=value</span>

步骤2. 对string1进行sha1签名,得到signature:

0f9de62fce790f9a083d5c99e95740ceb90c27ed

完整代码如下

<span style="color: #000000;">php</span><span style="color: #0000ff;">class</span><span style="color: #000000;"> JSSDK {  </span><span style="color: #0000ff;">private</span> <span style="color: #800080;">$appId</span><span style="color: #000000;">;  </span><span style="color: #0000ff;">private</span> <span style="color: #800080;">$appSecret</span><span style="color: #000000;">;  </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> __construct(<span style="color: #800080;">$appId</span>, <span style="color: #800080;">$appSecret</span><span style="color: #000000;">) {    </span><span style="color: #800080;">$this</span>->appId = <span style="color: #800080;">$appId</span><span style="color: #000000;">;    </span><span style="color: #800080;">$this</span>->appSecret = <span style="color: #800080;">$appSecret</span><span style="color: #000000;">;  }  </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> getSignPackage() {    </span><span style="color: #800080;">$jsapiTicket</span> = <span style="color: #800080;">$this</span>-><span style="color: #000000;">getJsApiTicket();    </span><span style="color: #008000;">//</span><span style="color: #008000;"> 注意 URL 一定要动态获取,不能 hardcode.</span>    <span style="color: #800080;">$protocol</span> = (!<span style="color: #0000ff;">empty</span>(<span style="color: #800080;">$_SERVER</span>['HTTPS']) && <span style="color: #800080;">$_SERVER</span>['HTTPS'] !== 'off' || <span style="color: #800080;">$_SERVER</span>['SERVER_PORT'] == 443) ? "https://" : "http://"<span style="color: #000000;">;    </span><span style="color: #800080;">$url</span> = "<span style="color: #800080;">$protocol$_SERVER</span>[HTTP_HOST]<span style="color: #800080;">$_SERVER</span>[REQUEST_URI]"<span style="color: #000000;">;    </span><span style="color: #800080;">$timestamp</span> = <span style="color: #008080;">time</span><span style="color: #000000;">();    </span><span style="color: #800080;">$nonceStr</span> = <span style="color: #800080;">$this</span>-><span style="color: #000000;">createNonceStr();    </span><span style="color: #008000;">//</span><span style="color: #008000;"> 这里参数的顺序要按照 key 值 ASCII 码升序排序</span>    <span style="color: #800080;">$string</span> = "jsapi_ticket=<span style="color: #800080;">$jsapiTicket</span>&noncestr=<span style="color: #800080;">$nonceStr</span>&timestamp=<span style="color: #800080;">$timestamp</span>&url=<span style="color: #800080;">$url</span>"<span style="color: #000000;">;    </span><span style="color: #800080;">$signature</span> = <span style="color: #008080;">sha1</span>(<span style="color: #800080;">$string</span><span style="color: #000000;">);    </span><span style="color: #800080;">$signPackage</span> = <span style="color: #0000ff;">array</span><span style="color: #000000;">(      </span>"appId"     => <span style="color: #800080;">$this</span>->appId,      "nonceStr"  => <span style="color: #800080;">$nonceStr</span>,      "timestamp" => <span style="color: #800080;">$timestamp</span>,      "url"       => <span style="color: #800080;">$url</span>,      "signature" => <span style="color: #800080;">$signature</span>,      "rawString" => <span style="color: #800080;">$string</span><span style="color: #000000;">    );    </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$signPackage</span><span style="color: #000000;">;   }  </span><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">function</span> createNonceStr(<span style="color: #800080;">$length</span> = 16<span style="color: #000000;">) {    </span><span style="color: #800080;">$chars</span> = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"<span style="color: #000000;">;    </span><span style="color: #800080;">$str</span> = ""<span style="color: #000000;">;    </span><span style="color: #0000ff;">for</span> (<span style="color: #800080;">$i</span> = 0; <span style="color: #800080;">$i</span> $length; <span style="color: #800080;">$i</span>++<span style="color: #000000;">) {      </span><span style="color: #800080;">$str</span> .= <span style="color: #008080;">substr</span>(<span style="color: #800080;">$chars</span>, <span style="color: #008080;">mt_rand</span>(0, <span style="color: #008080;">strlen</span>(<span style="color: #800080;">$chars</span>) - 1), 1<span style="color: #000000;">);    }    </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$str</span><span style="color: #000000;">;  }  </span><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> getJsApiTicket() {    </span><span style="color: #008000;">//</span><span style="color: #008000;"> jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例</span>    <span style="color: #800080;">$data</span> = json_decode(<span style="color: #008080;">file_get_contents</span>("jsapi_ticket.json"<span style="color: #000000;">));    </span><span style="color: #0000ff;">if</span> (<span style="color: #800080;">$data</span>->expire_time time<span style="color: #000000;">()) {      </span><span style="color: #800080;">$accessToken</span> = <span style="color: #800080;">$this</span>-><span style="color: #000000;">getAccessToken();      </span><span style="color: #008000;">//</span><span style="color: #008000;"> 如果是企业号用以下 URL 获取 ticket      // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";</span>      <span style="color: #800080;">$url</span> = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=<span style="color: #800080;">$accessToken</span>"<span style="color: #000000;">;      </span><span style="color: #800080;">$res</span> = json_decode(<span style="color: #800080;">$this</span>->httpGet(<span style="color: #800080;">$url</span><span style="color: #000000;">));      </span><span style="color: #800080;">$ticket</span> = <span style="color: #800080;">$res</span>-><span style="color: #000000;">ticket;      </span><span style="color: #0000ff;">if</span> (<span style="color: #800080;">$ticket</span><span style="color: #000000;">) {        </span><span style="color: #800080;">$data</span>->expire_time = <span style="color: #008080;">time</span>() + 7000<span style="color: #000000;">;        </span><span style="color: #800080;">$data</span>->jsapi_ticket = <span style="color: #800080;">$ticket</span><span style="color: #000000;">;        </span><span style="color: #800080;">$fp</span> = <span style="color: #008080;">fopen</span>("jsapi_ticket.json", "w"<span style="color: #000000;">);        </span><span style="color: #008080;">fwrite</span>(<span style="color: #800080;">$fp</span>, json_encode(<span style="color: #800080;">$data</span><span style="color: #000000;">));        </span><span style="color: #008080;">fclose</span>(<span style="color: #800080;">$fp</span><span style="color: #000000;">);      }    } </span><span style="color: #0000ff;">else</span><span style="color: #000000;"> {      </span><span style="color: #800080;">$ticket</span> = <span style="color: #800080;">$data</span>-><span style="color: #000000;">jsapi_ticket;    }    </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$ticket</span><span style="color: #000000;">;  }  </span><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> getAccessToken() {    </span><span style="color: #008000;">//</span><span style="color: #008000;"> access_token 应该全局存储与更新,以下代码以写入到文件中做示例</span>    <span style="color: #800080;">$data</span> = json_decode(<span style="color: #008080;">file_get_contents</span>("access_token.json"<span style="color: #000000;">));    </span><span style="color: #0000ff;">if</span> (<span style="color: #800080;">$data</span>->expire_time time<span style="color: #000000;">()) {      </span><span style="color: #008000;">//</span><span style="color: #008000;"> 如果是企业号用以下URL获取access_token      // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";</span>      <span style="color: #800080;">$url</span> = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=<span style="color: #800080;">$this</span>->appId&secret=<span style="color: #800080;">$this</span>->appSecret"<span style="color: #000000;">;      </span><span style="color: #800080;">$res</span> = json_decode(<span style="color: #800080;">$this</span>->httpGet(<span style="color: #800080;">$url</span><span style="color: #000000;">));      </span><span style="color: #800080;">$access_token</span> = <span style="color: #800080;">$res</span>-><span style="color: #000000;">access_token;      </span><span style="color: #0000ff;">if</span> (<span style="color: #800080;">$access_token</span><span style="color: #000000;">) {        </span><span style="color: #800080;">$data</span>->expire_time = <span style="color: #008080;">time</span>() + 7000<span style="color: #000000;">;        </span><span style="color: #800080;">$data</span>->access_token = <span style="color: #800080;">$access_token</span><span style="color: #000000;">;        </span><span style="color: #800080;">$fp</span> = <span style="color: #008080;">fopen</span>("access_token.json", "w"<span style="color: #000000;">);        </span><span style="color: #008080;">fwrite</span>(<span style="color: #800080;">$fp</span>, json_encode(<span style="color: #800080;">$data</span><span style="color: #000000;">));        </span><span style="color: #008080;">fclose</span>(<span style="color: #800080;">$fp</span><span style="color: #000000;">);      }    } </span><span style="color: #0000ff;">else</span><span style="color: #000000;"> {      </span><span style="color: #800080;">$access_token</span> = <span style="color: #800080;">$data</span>-><span style="color: #000000;">access_token;    }    </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$access_token</span><span style="color: #000000;">;  }  </span><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">function</span> httpGet(<span style="color: #800080;">$url</span><span style="color: #000000;">) {    </span><span style="color: #800080;">$curl</span> =<span style="color: #000000;"> curl_init();    curl_setopt(</span><span style="color: #800080;">$curl</span>, CURLOPT_RETURNTRANSFER, <span style="color: #0000ff;">true</span><span style="color: #000000;">);    curl_setopt(</span><span style="color: #800080;">$curl</span>, CURLOPT_TIMEOUT, 500<span style="color: #000000;">);    curl_setopt(</span><span style="color: #800080;">$curl</span>, CURLOPT_SSL_VERIFYPEER, <span style="color: #0000ff;">false</span><span style="color: #000000;">);    curl_setopt(</span><span style="color: #800080;">$curl</span>, CURLOPT_SSL_VERIFYHOST, <span style="color: #0000ff;">false</span><span style="color: #000000;">);    curl_setopt(</span><span style="color: #800080;">$curl</span>, CURLOPT_URL, <span style="color: #800080;">$url</span><span style="color: #000000;">);    </span><span style="color: #800080;">$res</span> = curl_exec(<span style="color: #800080;">$curl</span><span style="color: #000000;">);    curl_close(</span><span style="color: #800080;">$curl</span><span style="color: #000000;">);    </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$res</span><span style="color: #000000;">;  }}</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

2. 绑定域名

先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。

3. 获取签名包

<span style="color: #000000;">php</span><span style="color: #0000ff;">require_once</span> "jssdk.php"<span style="color: #000000;">;</span><span style="color: #800080;">$jssdk</span> = <span style="color: #0000ff;">new</span> JSSDK("yourAppID", "yourAppSecret"<span style="color: #000000;">);</span><span style="color: #800080;">$signPackage</span> = <span style="color: #800080;">$jssdk</span>-><span style="color: #000000;">GetSignPackage();</span>?>

4. 引入JS文件

在需要调用JS接口的页面引入如下JS文件:

特别注意:JS-SDK版本需使用http://res.wx.qq.com/open/js/jweixin-1.1.0.js

<span style="color: #0000ff;"><span style="color: #800000;">script </span><span style="color: #ff0000;">src</span><span style="color: #0000ff;">="http://res.wx.qq.com/open/js/jweixin-1.1.0.js"</span><span style="color: #0000ff;">></span><span style="color: #800000;">script</span><span style="color: #0000ff;">></span></span>

5.通过config接口注入权限验证配置

所有需要使用JS-SDK的页面必须先注入配置信息,否则将无法调用。

        <script><span style="color: #000000;">          wx.config({            debug: <span style="color: #0000ff;">false<span style="color: #000000;">,            appId: '<?php echo $signPackage["appId"];?>'<span style="color: #000000;">,            timestamp: <?php echo $signPackage["timestamp"];?><span style="color: #000000;">,            nonceStr: '<?php echo $signPackage["nonceStr"];?>'<span style="color: #000000;">,            signature: '<?php echo $signPackage["signature"];?>'<span style="color: #000000;">,            jsApiList: [              <span style="color: #008000;">//<span style="color: #008000;"> 所有要调用的 API 都要加到这个列表中                'checkJsApi'<span style="color: #000000;">,                'openAddress'<span style="color: #000000;">,              ]          });        </script>

5. 通过ready接口处理成功验证

需要在页面加载时就调用,需要把相关接口放在ready函数中调用来确保正确执行

wx.ready(<span style="color: #0000ff;">function</span><span style="color: #000000;"> () {});</span>

5.1 通过checkJsApi判断当前客户端版本是否支持分享参数自定义

 

<span style="color: #000000;"> wx.checkJsApi({                jsApiList: [                    </span>'openAddress'<span style="color: #000000;">,                ],                success: </span><span style="color: #0000ff;">function</span><span style="color: #000000;"> (res) {                    alert(JSON.stringify(res));                }            });</span>  

5.3. 实现收货地址共享

 

<span style="color: #000000;">            wx.openAddress({              trigger: </span><span style="color: #0000ff;">function</span><span style="color: #000000;"> (res) {                alert(</span>'用户开始拉出地址'<span style="color: #000000;">);              },              success: </span><span style="color: #0000ff;">function</span><span style="color: #000000;"> (res) {                alert(</span>'用户成功拉出地址'<span style="color: #000000;">);                alert(JSON.stringify(res));                document.form1.address1.value         </span>=<span style="color: #000000;"> res.provinceName;                document.form1.address2.value         </span>=<span style="color: #000000;"> res.cityName;                document.form1.address3.value         </span>=<span style="color: #000000;"> res.countryName;                document.form1.detail.value           </span>=<span style="color: #000000;"> res.detailInfo;                document.form1.national.value         </span>=<span style="color: #000000;"> res.nationalCode;                document.form1.user.value            </span>=<span style="color: #000000;"> res.userName;                document.form1.phone.value            </span>=<span style="color: #000000;"> res.telNumber;                document.form1.postcode.value         </span>=<span style="color: #000000;"> res.postalCode;                document.form1.errmsg.value         </span>=<span style="color: #000000;"> res.errMsg;                document.form1.qq.value             </span>= 1354386063<span style="color: #000000;">;              },              cancel: </span><span style="color: #0000ff;">function</span><span style="color: #000000;"> (res) {                alert(</span>'用户取消拉出地址'<span style="color: #000000;">);              },              fail: </span><span style="color: #0000ff;">function</span><span style="color: #000000;"> (res) {                alert(JSON.stringify(res));              }            });</span>

 

返回说明

返回值

说明

errMsg

获取编辑收货地址成功返回“openAddress:ok”。

userName

收货人姓名。

postalCode

邮编。

provinceName

国标收货地址第一级地址(省)。

cityName

国标收货地址第二级地址(市)。

countryName

国标收货地址第三级地址(国家)。

detailInfo

详细收货地址信息。

nationalCode

收货地址国家码。

 

三、实现效果

    

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Modern PHP读书笔记1Next article:使用PHP的cURL库