Detailed introduction to background development using Yii2 WeChat

Source: Internet
Author: User
Yii2 is a high-performance, component-based PHP Framework. This article details how to use Yii2 to develop the backend. Let's take a look. Yii2 is a high-performance, component-based PHP Framework. This article details how to use Yii2 to develop the backend. Let's take a look.

There are a lot of development tutorials on YII2.0 on the Internet, but they are too complicated and messy. so I am going to give you a summary of the series of Yii2 background development and give them a reference to all of you.

I. access

Yii2 background configuration

1. configure the token parameter in app/config/params. php.

Return [// access 'WeChat' => ['token' => 'Your token',],];

2. configure routes in app/config/main. php

Because the interface module uses RESTful APIs, you need to define routing rules.

'urlManager' => [ 'enablePrettyUrl' => true, 'enableStrictParsing' => true, 'showScriptName' => false, 'rules' => [ [  'class' => 'yii\rest\UrlRule',  'controller' => 'wechat',  'extraPatterns' => [  'GET valid' => 'valid',  ], ], ],],

3. create WechatController in app/controllers

 checkSignature($signature,$timestamp,$nonce)){  echo $echoStr; } } private function checkSignature($signature,$timestamp,$nonce) { // you must define TOKEN by yourself $token = Yii::$app->params['wechat']['token']; if (!$token) {  echo 'TOKEN is not defined!'; } else {  $tmpArr = array($token, $timestamp, $nonce);  // use SORT_STRING rule  sort($tmpArr, SORT_STRING);  $tmpStr = implode( $tmpArr );  $tmpStr = sha1( $tmpStr );  if( $tmpStr == $signature ){  return true;  }else{  return false;  } } }}

Public Account background configuration

Configure the URL and Token in the public account background, and then submit the verification.

URL:http://app.demo.com/wechats/validToken:your token

II. obtain user information

User table design

The code is as follows:

Create table 'WeChat _ user' ('id' int (11) not null, 'openid' varchar (255) COLLATE utf8_unicode_ci not null, 'nickname' varchar (50) COLLATE utf8_unicode_ci not null comment 'Nickname ', 'sex' tinyint (4) not null comment 'gender', 'headimgurl' varchar (255) COLLATE utf8_unicode_ci not null comment 'Avatar ', 'Country' varchar (50) COLLATE utf8_unicode_ci not null comment 'Country ', 'Province' varchar (50) COLLATE utf8_unicode_ci not null comment' province ', 'City' varchar (50) COLLATE utf8_unicode_ci not null comment 'city', 'Access _ token' varchar (255) COLLATE utf8_unicode_ci not null, 'refresh_token' varchar (255) COLLATE utf8_unicode_ci not null, 'created _ at' timestamp null default CURRENT_TIMESTAMP) ENGINE = InnoDB AUTO_INCREMENT = 4 default charset = utf8 COLLATE = utf8_unicode_ci; alter table 'WeChat _ user' add primary key ('id ');

Interface for getting user information

1. user authorization interface: get access_token and openId; get and save user information to the database

The code is as follows:

Public function actionAccesstoken () {$ code = $ _ GET ["code"]; $ state = $ _ GET ["state"]; $ appid = Yii :: $ app-> params ['cmd'] ['appid ']; $ appsecret = Yii: $ app-> params ['cmd'] ['appsecret']; $ request_url =' https://api.weixin.qq.com/sns/oauth2/access_token?appid= '. $ Appid. '& secret = '. $ appsecret. '& code = '. $ code. '& grant_type = authorization_code'; // initialize a curl session $ ch = curl_init (); curl_setopt ($ ch, CURLOPT_URL, $ request_url); curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, true); $ result = curl_exec ($ ch); curl_close ($ ch); $ result = $ this-> response ($ result); // token and openid are successfully obtained, data parsing $ access_token = $ result ['Access _ token']; $ refresh_token = $ result ['refresh _ token']; $ openid = $ result ['openid']; // request interface, get user information $ userInfo = $ this-> getUserInfo ($ access_token, $ openid); $ user_check = WechatUser: find () -> where (['openid' => $ openid])-> one (); if ($ user_check) {// update user information} else {// save user information} // redirect of the front-end webpage if ($ openid) {return $ this-> redirect ($ state. $ openid) ;}else {return $ this-> redirect ($ state );}}

2. obtain user information

The code is as follows:

Public function getUserInfo ($ access_token, $ openid) {$ request_url = 'https: // api.weixin.qq.com/sns/userinfo? Access_token = '. $ access_token. '& openid = '. $ openid. '& lang = zh_CN'; // initialize a curl session $ ch = curl_init (); curl_setopt ($ ch, CURLOPT_URL, $ request_url); curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, true); $ result = curl_exec ($ ch); curl_close ($ ch); $ result = $ this-> response ($ result); return $ result ;}

3. user data retrieval interface

Public function actionUserinfo () {if (isset ($ _ REQUEST ["openid"]) {$ openid = $ _ REQUEST ["openid"]; $ user = WechatUser :: find ()-> where (['openid' => $ openid])-> one (); if ($ user) {$ result ['error'] = 0; $ result ['MSG '] = 'obtained successfully'; $ result ['user'] = $ user;} else {$ result ['error'] = 1; $ result ['MSG '] =' no user ';} else {$ result ['error'] = 1; $ result ['MSG '] = 'openid is blank';} return $ result ;}

III. payment

1. Payment Interface: Package payment data

The code is as follows:

Public function actionPay () {if (isset ($ _ REQUEST ["uid"]) & isset ($ _ REQUEST ["oid"]) & isset ($ _ REQUEST ["totalFee"]) {// uid, oid, totalFee $ uid =$ _ REQUEST ["uid"]; $ oid = $ _ REQUEST ["oid"]; $ totalloud = $ _ REQUEST ["totalloud"]; $ timestamp = time (); // payment parameter $ appid = Yii:: $ app-> params ['cmd'] ['appid ']; $ mchid = Yii: $ app-> params ['cmd'] ['mchid']; $ key = Yii: $ app-> params ['WeChat'] ['key']; $ policyurl = Yii :: $ app-> params ['WeChat'] ['policyurl']; // payment package $ wx_pay = new WechatPay ($ mchid, $ appid, $ key ); $ package = $ wx_pay-> createJsBizPackage ($ uid, $ total.pdf, $ oid, $ policyurl, $ timestamp); $ result ['error'] = 0; $ result ['MSG '] = 'payment package succeeded'; $ result ['package'] = $ package; return $ result ;} else {$ result ['error'] = 1; $ result ['MSG '] = 'Request parameter error';} return $ result ;}

2. receive asynchronous payment result notifications

The code is as follows:

Public function actionNotify () {$ postStr = $ GLOBALS ["HTTP_RAW_POST_DATA"]; $ postObj = simplexml_load_string ($ postStr, 'simplexmlelement', LIBXML_NOCDATA ); // if ($ postObj = false) {die ('parse xml error');} if ($ postObj-> return_code! = 'Success') {die ($ postObj-> return_msg);} if ($ postObj-> result_code! = 'Success') {die ($ postObj-> err_code);} // payment parameter $ appid = Yii :: $ app-> params ['cmd'] ['appid ']; $ mchid = Yii: $ app-> params ['cmd'] ['mchid']; $ key = Yii: $ app-> params ['WeChat'] ['key']; $ wx_pay = new WechatPay ($ mchid, $ appid, $ key ); // verify the signature $ arr = (array) $ postObj; unset ($ arr ['sign']); if ($ wx_pay-> getSign ($ arr, $ key )! = $ PostObj-> sign) {die ("signature error");} // the payment process is correct-determine whether the payment status has been processed $ orders = Order: find () -> where (['uid' => $ postObj-> openid, 'id' => $ postObj-> out_trade_no, 'status' => 0]) -> all (); if (count ($ orders)> 0) {// update order status foreach ($ orders as $ order) {// update order $ order ['status'] = 1; $ order-> update ();} return'
 
  SUCCESS
  
  OK
  
 ';} Else {// The order status has been updated, and return directly'
 
  SUCCESS
  
  OK
  
 ';}}

3. payment class WechatPay. php

The code is as follows:

 Mchid = $ mchid; $ this-> appid = $ appid; $ this-> key = $ key;} public function createJsBizPackage ($ openid, $ totalFee, $ outTradeNo, $ orderName, $ notifyUrl, $ timestamp) {$ config = array ('mch _ id' => $ this-> mchid, 'appid '=> $ this-> appid, 'key' => $ this-> key,); $ uniied = array ('appid '=> $ config ['appid'], 'Attach '=> 'pay ', 'Body' => $ orderName, 'mch _ id' => $ config ['mch _ id'], 'nonce _ str' => self: createNonceStr (), 'Your y _ url' => $ notifyUrl, 'openid' => $ openid, 'Out _ trade_no '=> $ outTradeNo, 'spbill _ create_ip' => '2017. 0.0.1 ', 'total _ region' => intval ($ totalFee * 100), 'Trade _ type' => 'jsapi ',); $ uniied ['sign'] = self: getSign ($ uniied, $ config ['key']); $ responseXml = self: curlPost (' https://api.mch.weixin.qq.com/pay/unifiedorder ', Self: arrayToXml ($ unified); $ unifiedOrder = simplexml_load_string ($ responseXml, 'simplexmlelement', LIBXML_NOCDATA); if ($ unigiedorder = false) {die ('parse xml error');} if ($ unifiedOrder-> return_code! = 'Success') {die ($ unigiedorder-> return_msg);} if ($ unigiedorder-> result_code! = 'Success') {die ($ unifiedOrder-> err_code);} $ arr = array ("appId" => $ config ['appid '], "timeStamp" => $ timestamp, "nonceStr" => self: createNonceStr (), "package" => "prepay_id = ". $ unifiedOrder-> prepay_id, "signType" => 'md5',); $ arr ['paysign'] = self: getSign ($ arr, $ config ['key']); return $ arr;} public static function curlGet ($ url = '', $ options = array ()) {$ ch = curl_init ($ url); curl_setopt ($ Ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ ch, CURLOPT_TIMEOUT, 30); if (! Empty ($ options) {curl_setopt_array ($ ch, $ options);} // https requests do not verify the certificate and host curl_setopt ($ ch, CURLOPT_SSL_VERIFYPEER, false ); curl_setopt ($ ch, CURLOPT_SSL_VERIFYHOST, false); $ data = curl_exec ($ ch); curl_close ($ ch); return $ data ;} public static function curlPost ($ url = '', $ postData ='', $ options = array () {if (is_array ($ postData )) {$ postData = http_build_query ($ postData);} $ ch = curl_init (); c Url_setopt ($ ch, CURLOPT_URL, $ url); curl_setopt ($ ch, batch, 1); curl_setopt ($ ch, CURLOPT_POST, 1); curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ postData); curl_setopt ($ ch, CURLOPT_TIMEOUT, 30); // sets the maximum number of seconds that cURL can be executed if (! Empty ($ options) {curl_setopt_array ($ ch, $ options);} // https requests do not verify the certificate and host curl_setopt ($ ch, CURLOPT_SSL_VERIFYPEER, false ); curl_setopt ($ ch, CURLOPT_SSL_VERIFYHOST, false); $ data = curl_exec ($ ch); curl_close ($ ch); return $ data;} public static function createNonceStr ($ length = 16) {$ chars = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789 '; $ str = ''; for ($ I = 0; $ I <$ length; $ I ++) {$. str. = substr ($ chars, mt_rand (0, strlen ($ chars)-1), 1) ;}return $ str ;} public static function arrayToXml ($ arr) {$ xml ="
 
  
"; Foreach ($ arr as $ key => $ val) {if (is_numeric ($ val) {$ xml. = "<". $ key. "> ". $ val."
  ";} Else {$ xml. =" <". $ key.">" . $val . "
  ";}}$ Xml. ="
 "; Return $ xml;} public static function getSign ($ params, $ key) {ksort ($ params, SORT_STRING); $ unSignParaString = self: formatQueryParaMap ($ params, false); $ signStr = strtoupper (md5 ($ unSignParaString. "& key = ". $ key); return $ signStr;} protected static function formatQueryParaMap ($ paraMap, $ urlEncode = false) {$ buff = ""; ksort ($ paraMap ); foreach ($ paraMap as $ k =>$ v) {if (null! = $ V & "null "! = $ V) {if ($ urlEncode) {$ v = urlencode ($ v);} $ buff. = $ k. "= ". $ v. "&" ;}}$ reqPar = ''; if (strlen ($ buff)> 0) {$ reqPar = substr ($ buff, 0, strlen ($ buff) -1);} return $ reqPar ;}}

4. get the config parameters of the JS-SDK

According to the public platform developer documentation:

All pages that require JS-SDK must first inject configuration information, otherwise it will not be called (the same url only needs to be called once, the SPA web app that changes the url can be called every time the url changes. Currently, the Android client does not support the new H5 feature of pushState, therefore, using pushState to implement web app pages will cause signature failure, which will be fixed in Android6.2 ).

That is:

The code is as follows:

Wx. config ({debug: true, // enable the debugging mode. The Returned values of all called APIs are displayed in the client alert. to view the input parameters, you can open them on the pc, the parameter information is output through log and printed only on the pc end. AppId: '', // required. the unique identifier timestamp:, // required. the timestamp of the generated signature is nonceStr:''. // required, sign the random string signature: '', // required. for details, see Appendix 1 jsApiList: [] // required. list of JS interfaces to be used, for a list of all JS interfaces, see Appendix 2 });

1. payment class WechatPay. php

The code is as follows:

 $ This-> appid, "nonceStr" => $ nonceStr, "timestamp" => $ timestamp, "url" => $ url, "signature" => $ signature, "rawString" => $ string); return $ signPackage;} public static function getJsApiTicket () {// use Redis to cache jsapi_ticket $ redis = Yii: $ app-> redis; $ redis_ticket = $ redis-> get ('WeChat: jsapi_ticket '); if ($ redis_ticket) {$ ticket = $ redis_ticket;} else {$ accessToken = self :: getAccessToken (); $ url =" https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token= ". $ AccessToken; $ res = json_decode (self: curlGet ($ url); $ ticket = $ res-> ticket; if ($ ticket) {$ redis-> set ('WeChat: jsapi_ticket ', $ ticket); $ redis-> expire ('WeChat: jsapi_ticket', 7000);} return $ ticket ;} public static function getAccessToken () {// use the Redis Cache access_token $ redis = Yii ::$ app-> redis; $ redis_token = $ redis-> get ('WeChat: access_token '); if ($ redis_token) {$ access_token = $ redis_token;} else {$ appid = Yii :: $ app-> params ['cmd'] ['appid ']; $ appsecret = Yii: $ app-> params ['cmd'] ['appsecret']; $ url =" https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid= ". $ Appid. "& secret = ". $ appsecret; $ res = json_decode (self: curlGet ($ url); $ access_token = $ res-> access_token; if ($ access_token) {$ redis-> set ('WeChat: access_token', $ access_token); $ redis-> expire ('WeChat: access_token', 7000);} return $ access_token ;} public static function curlGet ($ url = '', $ options = array () {$ ch = curl_init ($ url); curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt ($ ch, CURLOPT_TIMEOUT, 30); if (! Empty ($ options) {curl_setopt_array ($ ch, $ options);} // https requests do not verify the certificate and host curl_setopt ($ ch, CURLOPT_SSL_VERIFYPEER, false ); curl_setopt ($ ch, CURLOPT_SSL_VERIFYHOST, false); $ data = curl_exec ($ ch); curl_close ($ ch); return $ data ;} public static function curlPost ($ url = '', $ postData ='', $ options = array () {if (is_array ($ postData )) {$ postData = http_build_query ($ postData);} $ ch = curl_init (); c Url_setopt ($ ch, CURLOPT_URL, $ url); curl_setopt ($ ch, batch, 1); curl_setopt ($ ch, CURLOPT_POST, 1); curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ postData); curl_setopt ($ ch, CURLOPT_TIMEOUT, 30); // sets the maximum number of seconds that cURL can be executed if (! Empty ($ options) {curl_setopt_array ($ ch, $ options);} // https requests do not verify the certificate and host curl_setopt ($ ch, CURLOPT_SSL_VERIFYPEER, false ); curl_setopt ($ ch, CURLOPT_SSL_VERIFYHOST, false); $ data = curl_exec ($ ch); curl_close ($ ch); return $ data;} public static function createNonceStr ($ length = 16) {$ chars = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789 '; $ str = ''; for ($ I = 0; $ I <$ length; $ I ++) {$. str. = substr ($ chars, mt_rand (0, strlen ($ chars)-1), 1) ;}return $ str ;}}

2. get the config parameter interface

Public function actionConfig () {if (isset ($ _ REQUEST ['URL']) {$ url = $ _ REQUEST ['URL']; // payment parameter $ appid = Yii: $ app-> params ['WeChat '] ['appid']; $ mchid = Yii :: $ app-> params ['cmd'] ['mkid']; $ key = Yii: $ app-> params ['cmd'] ['key']; $ wx_pay = new WechatPay ($ mchid, $ appid, $ key); $ package = $ wx_pay-> getSignPackage ($ url); $ result ['error'] = 0; $ result ['MSG '] = 'obtained successfully'; $ result ['config'] = $ package;} else {$ result ['error'] = 1; $ result ['MSG '] = 'parameter error';} return $ result ;}

The above is a detailed description of the background development using Yii2. For more information, see other related articles on php Chinese network!

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.