WeChat payment development (7) shipping address sharing Interface V2, v2_PHP tutorial

Source: Internet
Author: User
Tags sha1 encryption
Payment development (7) shipping address sharing Interface V2, v2. Payment development (7) receiving address sharing Interface V2, v2 keyword: public platform JSSDK send to a friend receiving address sharing interface openAddress author: Fang times studio Original article: htt payment development (7) shipping address sharing Interface V2, v2

Keywords: public platform JSSDK send to a friend receiving address sharing interface openAddress
Author: Fang times Studio
Original article: http://www.cnblogs.com/txw1958/p/weixin-openaddress.html

In this public platform development tutorial, we will introduce how to obtain the shipping address on the webpage.

The shipping address sharing interface was upgraded in December April 13, 2016, and only new interfaces can be used in December May 20, 2016. this tutorial is a new interface tutorial!

This article consists of the following two parts:

1. JS-SDK1. get Access Token

Access token acquisition method is described earlier. for details, see public platform development (26) ACCESS TOKEN

2. get jsapi_ticket

Before generating a signature, you must first understand jsapi_ticket. jsapi_ticket is a temporary ticket used by the public account to call the JS interface. Under normal circumstances, jsapi_ticket is valid for 7200 seconds and obtained through access_token. Because jsapi_ticket has a limited number of api calls, refreshing jsapi_ticket frequently limits api calls and affects your business. developers must cache jsapi_ticket globally in their own services.

Refer to the following document to obtain access_token (valid for 7200 seconds, the developer must cache access_token in the global cache of his/her service ):
Use the access_token obtained in the first step to request jsapi_ticket through http GET (valid for 7200 seconds, developers must cache jsapi_ticket globally in their own services). The interface address is as follows:

https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi

The following JSON is returned:

{    "errcode":0,    "errmsg":"ok",    "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",    "expires_in":7200}

After obtaining jsapi_ticket, you can generate a signature for JS-SDK permission verification.

3. signature algorithm implementation

The signature generation rules are as follows: The fields involved in the signature include noncestr (random string), valid jsapi_ticket, timestamp (timestamp), url (URL of the current webpage, does not contain # and the following parts ). After all parameters to be signed are sorted in ascending order (lexicographically) according to the field name ASCII code, the format of the URL Key-value pair is used (that is, key1 = value1 & key2 = value2 ...) Concatenate the string into string1. Note that all parameter names are lowercase characters. Perform sha1 encryption on string1, and use original values for field names and field values without URL escaping.

Signature = sha1 (string1 ). Example:

noncestr=Wm3WZYTPz0wzccnWjsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qgtimestamp=1414587457url=http://mp.weixin.qq.com?params=value

Step 1. sort all parameters to be signed in ascending order of the ASCII code of field names (lexicographically), and then use the format of the URL Key-value pair (that is, key1 = value1 & key2 = value2 ...) Concatenate the string into string1:

jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW&timestamp=1414587457&url=http://mp.weixin.qq.com?params=value

Step 2. sign string1 sha1 to obtain signature:

0f9de62fce790f9a083d5c99e95740ceb90c27ed

The complete code is as follows:

 AppId = $ appId; $ this-> appSecret = $ appSecret;} public function getSignPackage () {$ jsapiTicket = $ this-> getJsApiTicket (); // note that the URL must be dynamically obtained and cannot be hardcode. $ protocol = (! Empty ($ _ SERVER ['https']) & $ _ SERVER ['https']! = 'Off' | $ _ SERVER ['server _ port'] = 443 )? "Https: //": "http: //"; $ url = "$ protocol $ _ SERVER [HTTP_HOST] $ _ SERVER [REQUEST_URI]"; $ timestamp = time (); $ nonceStr = $ this-> createNonceStr (); // the order of parameters here should be sorted by the key value ASCII code in ascending order $ string = "jsapi_ticket = $ jsapiTicket & noncestr = $ nonceStr & timestamp = $ timestamp & url = $ url "; $ signature = sha1 ($ string); $ signPackage = array ("appId" => $ this-> appId, "nonceStr" => $ nonceStr, "timestamp" => $ timestamp, "url" => $ url, "signature" => $ signature, "rawString" => $ string); return $ signPackage ;} private function createNonceStr ($ length = 16) {$ chars = "bytes"; $ str = ""; for ($ I = 0; $ I <$ length; $ I ++) {$ str. = substr ($ chars, mt_rand (0, strlen ($ chars)-1), 1) ;}return $ str ;} private function getJsApiTicket () {// jsapi_ticket should be globally stored and Updated. the following code is written to the file as an example $ data = json_decode (file_get_contents ("jsapi_ticket.json ")); if ($ data-> expire_time <time () {$ accessToken = $ this-> getAccessToken (); // if the enterprise ID is used, use the following URL to obtain ticket // $ url =" https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token= $ AccessToken "; $ url =" https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token= $ AccessToken "; $ res = json_decode ($ this-> httpGet ($ url); $ ticket = $ res-> ticket; if ($ ticket) {$ data-> expire_time = time () + 7000; $ data-> jsapi_ticket = $ ticket; $ fp = fopen ("jsapi_ticket.json", "w "); fwrite ($ fp, json_encode ($ data); fclose ($ fp) ;}} else {$ ticket = $ data-> jsapi_ticket;} return $ ticket ;} private function getAccessToken () {// access_token should be stored and updated globally. the following code is written to the file for example $ data = json_decode (file_get_contents ("access_token.json ")); if ($ data-> expire_time <time () {// if the enterprise ID is used, use the following URL to obtain access_token // $ url =" https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid= $ This-> appId & Cortana Cret = $ this-> appSecret "; $ url =" https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid= $ This-> appId & secret = $ this-> appSecret "; $ res = json_decode ($ this-> httpGet ($ url); $ access_token = $ res-> access_token; if ($ access_token) {data data-> expire_time = time () + 7000; $ data-> access_token = $ access_token; $ fp = fopen ("access_token.json ", "w"); fwrite ($ fp, json_encode ($ data); fclose ($ fp) ;}} else {$ access_token = $ data-> access_token ;} return $ access_token;} private function httpGet ($ url) {$ curl = curl_init (); curl_setopt ($ curl, CURLOPT_RETURNTRANSFER, true); curl_setopt ($ curl, CURLOPT_TIMEOUT, 500 ); curl_setopt ($ curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt ($ curl, expires, false); curl_setopt ($ curl, CURLOPT_URL, $ url); $ res = curl_exec ($ curl ); curl_close ($ curl); return $ res ;}}

II. shipping address sharing interface I. INTRODUCTION

Shipping address sharing means that after you open a webpage in your browser and enter the address, you can quickly select or add or edit the address without entering it. This address is a user attribute and can be shared on the webpage of each merchant. Native controls are supported to enter the address, and the address data is transmitted to the merchant.

Address sharing is implemented based on JavaScript APIs and can only be used in built-in browsers. other browser calls are invalid. At the same time, Version 5.0 is required. we recommend that you use the user agent to determine the current version number and then call the address interface. Take the iPhone version as an example. you can use useragent to obtain the following sample information: "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 indicates the version number installed by the user. the merchant can determine whether the version number is higher than or equal to 5.0.

Address format
Data fields used for address sharing include:

  • Recipient name
  • Level 3, region, province, city
  • Detailed address
  • Zip Code
  • Contact number

The region corresponds to the third-level geocode of the national standard, for example, "Guangdong province-Guangzhou-Tianhe District", and the corresponding zip code is 510630. Http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/201401/t20140116_501070.html for details

2. bind a domain name

Log on to the public platform and go to "function settings" of "public Account Settings" and enter "JS interface security domain name ".

3. obtain the signature package
 GetSignPackage();?>
4. introduce JS files

Introduce the following JS file on the page for calling the JS interface:

Special note: JS-SDK versions require http://res.wx.qq.com/open/js/jweixin-1.1.0.js

 
5. inject the permission verification configuration through the config interface 

All pages that require JS-SDK must first inject configuration information, otherwise they will not be called.

Script wx. config ({debug: false, appId :'
 ', Timestamp:
 , NonceStr :'
 ', Signature :'
 ', JsApiList: [// All the APIs to be called must be added to the list 'checkjsapi', 'openaddress',]}); script

5. verify the processing by using the ready interface

It must be called when the page is loaded. you need to place the related interfaces in the ready function to ensure correct execution.

wx.ready(function () {});

5.1 use checkJsApi to determine whether the current client version supports custom sharing parameters

 wx.checkJsApi({                jsApiList: [                    'openAddress',                ],                success: function (res) {                    alert(JSON.stringify(res));                }            });  

5.3. share the shipping address

Wx. openAddress ({trigger: function (res) {alert ('User start pulling address');}, success: function (res) {alert ('User successfully pulled address '); alert (JSON. stringify (res); document. form1.address1. value = res. provinceName; document. form1.address2. value = res. cityName; document. form1.address3. value = res. countryName; document. form1.detail. value = res. detailInfo; document. form1.national. value = res. nationalCode; document. form1.user. value = res. userName; document. form1.phone. value = res. telNumber; document. form1.postcode. value = res. postalCode; document. form1.errmsg. value = res. errMsg; document. form1.qq. value = 1354386063 ;}, cancel: function (res) {alert ('User cancel pulling address') ;}, fail: function (res) {alert (JSON. stringify (res ));}});

Return description

Return value

Description

ErrMsg

After obtaining and editing the shipping address, "openAddress: OK" is returned ".

UserName

The name of the receiver.

PostalCode

Zip code.

ProvinceName

National standard delivery address Level 1 address (province ).

CityName

The second-level address (city) of the national standard receiving address ).

CountryName

National standard receiving Address Level 3 address (country ).

DetailInfo

Detailed shipping address information.

NationalCode

Country code of the shipping address.

III. implementation results

Notify (7) receiving address sharing Interface V2, v2 keyword: public platform JSSDK send to a friend receiving address sharing interface openAddress author: Fang times studio original: htt...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.